按键跳跃在unity中的代码
时间: 2023-05-27 21:07:22 浏览: 78
以下是按键跳跃在Unity中的代码示例:
```csharp
public class PlayerController : MonoBehaviour
{
public float jumpForce = 10f;
public float moveSpeed = 5f;
public Transform groundCheck;
public LayerMask groundMask;
private Rigidbody2D rb;
private Animator anim;
private bool isGrounded;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
private void Update()
{
// 检测是否在地面上
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundMask);
// 跳跃
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
anim.SetTrigger("Jump");
}
// 左右移动
float moveDirection = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveDirection * moveSpeed, rb.velocity.y);
// 动画
anim.SetFloat("Speed", Mathf.Abs(moveDirection));
if (moveDirection < 0)
{
transform.localScale = new Vector3(-1, 1, 1);
}
else if (moveDirection > 0)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
}
```
上述代码中,首先定义了一些公共变量,包括跳跃力度、移动速度、检测地面的物体、地面的LayerMask。在Start()方法中获取了Rigidbody2D和Animator组件。在Update()方法中,首先检测是否在地面上,如果是,则可以跳跃。然后检测左右移动的方向,根据方向设置Rigidbody2D的velocity。最后根据移动方向和跳跃状态设置Animator的参数。
阅读全文