用C#写出一段玩家用键盘wasd操控角色前后左右移动的Unity 3d代码
以下是一段C#代码,用于玩家使用键盘wasd操控角色前后左右移动的Unity 3D游戏中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f; // 玩家移动速度
private Rigidbody playerRigidbody; // 玩家刚体
// Start is called before the first frame update
void Start()
{
playerRigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
// 获取玩家输入
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
// 计算移动方向
Vector3 moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput);
// 根据玩家输入移动玩家角色
playerRigidbody.AddForce(moveDirection * speed);
}
}
在这个脚本中,我们首先定义了一个公共的浮点型变量speed,用于表示玩家移动速度。然后,我们获取了玩家角色的Rigidbody组件,并在Update函数中获取玩家输入,并根据输入计算出移动方向。最后,我们使用AddForce函数移动玩家角色。注意,这段代码只实现了移动,如果需要实现更多的操作,需要在代码中添加相应的功能
原文地址: https://www.cveoy.top/t/topic/hvae 著作权归作者所有。请勿转载和采集!