代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Scripting.APIUpdating;
public class PlayerController : MonoBehaviour
{
public PlayerInputControl inputControl;
private Rigidbody2D rb;
public Vector2 inputDirection;
public float speed;
private void Awake()
{
inputControl = new PlayerInputControl();
// 获取 Player 上面的刚体组件
rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
inputControl.Enable();
}
private void OnDisable()
{
inputControl.Disable();
}
private void Update()
{
inputDirection = inputControl.Gameplay.Move.ReadValue<Vector2>();
}
private void FixedUpdate()
{
// 在 FixedUpdate 里面对刚体进行操作
Move();
}
public void Move()
{
// 设置刚体的速度,这样刚体就能移动了
rb.velocity = new Vector2(inputDirection.x * speed, rb.velocity.y);
// 初始人物是面朝 x 轴正方向的
int faceDir = 0;
if (transform.localScale.x > 0)
{
faceDir = 1;
}
else if (transform.localScale.x < 0)
{
faceDir = -1;
}
// 输入是 x 轴正方向的时候面朝也是 x 轴正方向
// 输入是 x 轴负方向的时候面朝也是 x 轴负方向
if (inputDirection.x > 0)
{
faceDir = 1;
}
if (inputDirection.x < 0)
{
faceDir = -1;
}
// 人物翻转
transform.localScale = new Vector3(faceDir * Mathf.Abs(transform.localScale.x), transform.localScale.y, transform.localScale.z);
}
}
项目相关代码
代码仓库:https://gitee.com/nbda1121440/2DAdventure.git
标签:20240424_0220