[Unity] Player4-实现人物跳跃

230 阅读1分钟

实现人物跳跃

  • 1.添加按键绑定 image.png

  • 2.编写代码

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    public PlayerInputControl inputControl;
    private Rigidbody2D rb;
    public Vector2 inputDirection;

    [Header("基本功能")]
    public float speed;
    public float jumpForce;


    private void Awake()
    {
        inputControl = new PlayerInputControl();
        rb = GetComponent<Rigidbody2D>();

        // 跳跃
        inputControl.Gameplay.Jump.started += Jump; // += 是事件注册(类似回调?)
    }


    private void OnEnable()
    {
        inputControl.Enable();
    }

    private void OnDisable()
    {
        inputControl.Disable();
    }

    private void Update()
    {
        // 这个Gameplay是添加Player Input时创建的,改名的,虽然后面删除了组件
        inputDirection = inputControl.Gameplay.Move.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        Move();
    }

    public void Move()
    {

        // 人物移动
        rb.velocity = new Vector2(inputDirection.x * speed * Time.deltaTime, rb.velocity.y);

        // 人物翻转
        int faceDir = (int)transform.localScale.x; // 面向方向
        if (inputDirection.x > 0)
            faceDir = 1;
        if (inputDirection.x < 0)
            faceDir = -1;
        transform.localScale = new Vector3(faceDir, 1, 1);
    }

    
    // 跳跃
    private void Jump(InputAction.CallbackContext context)
    {
        // Debug.Log("JUmp");
        rb.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
    }
}

  • 3.参数配置

image.png