以下是一个简单的玩家控制代码:

public class PlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 10f;
    private Rigidbody2D rb;
    private Animator animator;
    private bool isGrounded = false;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        // 移动
        float move = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(move * moveSpeed, rb.velocity.y);

        // 跳跃
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
            isGrounded = false;
            animator.SetTrigger("Jump");
        }

        // 动画
        animator.SetFloat("Speed", Mathf.Abs(move));
        animator.SetBool("Grounded", isGrounded);
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        // 碰到地面时设置 isGrounded 为 true
        if (coll.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }
}

以上代码包括了移动、跳跃和动画三个方面的实现,其中动画需要用到 Animator 组件。在碰到地面时,会设置 isGrounded 为 true,确保玩家能够跳跃。需要注意的是,此代码并不完整,需要根据具体需求进行修改和扩展。

我想在unity中做一个类黑魂的游戏请给出玩家控制代码

原文地址: https://www.cveoy.top/t/topic/bbAs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录