📅  最后修改于: 2023-12-03 15:20:51.498000             🧑  作者: Mango
In this tutorial, we will be creating a simple 2D jump mechanic in Unity using C#. This tutorial assumes basic knowledge of Unity, C# and 2D game design.
GameObject
by right-clicking in the Hierarchy
panel and selecting Create Empty
.GameObject
to something like Player
.SpriteRenderer
component to the Player
object by clicking the Add Component
button in the Inspector
panel and typing SpriteRenderer
in the search bar. Select this component once it appears.Rigidbody2D
component to the Player
object by clicking the Add Component
button in the Inspector
panel and typing Rigidbody2D
in the search bar. Select this component once it appears.GameObject
by right-clicking in the Hierarchy
panel and selecting Create Empty
.GameObject
to something like Ground
.SpriteRenderer
component to this GameObject
.BoxCollider2D
component to this GameObject
.Project
panel and selecting Create/C# Script
.PlayerJump
.PlayerJump
script:using UnityEngine;
public class PlayerJump : MonoBehaviour
{
[SerializeField] private float jumpForce = 5f;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private Transform groundCheck;
private Rigidbody2D rb;
private bool isGrounded = false;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer);
}
private void Update()
{
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpForce;
}
}
}
PlayerJump
script from the Project
panel and drop it onto the Player
object in the Hierarchy
panel.Ground
object in the Hierarchy
panel.Inspector
panel, check the Is Trigger
checkbox on the BoxCollider2D
component and set the size
to the size of your ground sprite.Project
panel, click on the Layers
dropdown menu and select Edit Layers...
.Ground
.Ground
object in the Hierarchy
panel.Inspector
panel, change the Layer
dropdown to Ground
.Player
object in the Hierarchy
panel.Inspector
panel, drag the Ground
object from the Hierarchy
panel to the Ground Check
field on the PlayerJump
component.Play
in Unity and test your game by jumping on and off the ground.In this tutorial, we created a simple 2D jump mechanic in Unity using C#. By following these steps, you should now have a basic understanding of how to script player movement in Unity.