Unity方向键控制物体移动与跳跃
功能描述
实现使用方向键控制物体在平面上移动,并使用空格键实现跳跃。
实现步骤
添加3D物体:在场景中创建一个3D物体,作为跟随鼠标移动的物体。
创建地面物体:在场景中创建一个平面(Plane),作为指定的地面物体,并为其设置一个Tag(例如Ground
)。
脚本代码:
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f; // 移动速度
public float jumpForce = 5f; // 跳跃力度
private bool isGrounded; // 是否在地面上
private Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// 获取输入
float moveHorizontal = Input.GetAxisRaw("Horizontal"); // 使用 GetAxisRaw
float moveVertical = Input.GetAxisRaw("Vertical"); // 使用 GetAxisRaw
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical).normalized;
// 移动
rb.velocity = new Vector3(movement.x * moveSpeed, rb.velocity.y, movement.z * moveSpeed);
}
// Update is called once per frame
void Update()
{
// 跳跃
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
void OnCollisionEnter(Collision collision)
{
// 检测是否在地面上
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
}
应用到物体:
-
将该脚本附加到你想要控制的物体上(例如一个立方体或角色模型)。
-
确保该物体有一个
Rigidbody
组件,以便应用物理效果。
调整参数:在Inspector窗口中,可以调整moveSpeed
和jumpForce
的值,以控制移动速度和跳跃高度
注意事项:
-
确保物体的
Rigidbody
组件没有勾选Is Kinematic
,否则物理效果将不会生效。 -
如果物体在移动时滑动过多,可以调整
Rigidbody
的Drag
值来增加阻力。
通过以上步骤,实现了使用方向键控制物体在Ground
平面上移动,并使用空格键实现跳跃。