1.Player脚本控制人物移动,可单独使用。(人物需添加组件Box Collider和Rigidbody)
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
Vector3 moveDirection;
Rigidbody rb;
float speed = 20.0f;
float jumpHeight = 0;
//初始化
void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void setSpeed(float speeds)
{
speed = speeds;
}
void Update()
{
if (speed == 0) return;
float steer = 20;
float x = Input.GetAxis("Horizontal");
transform.Rotate(0, x * steer * Time.deltaTime, 0);
if (Input.GetKey(KeyCode.H))
{
speed = 50.0f;
}
else {
speed = 20f;
}
float y = Input.GetAxis("Vertical");
Vector3 s = y * transform.forward * speed * Time.deltaTime;
transform.transform.position += s;
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
public void run() {
//控制人物上下左右移动
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
float moveUp = Input.GetKey(KeyCode.Space) ? 1 : 0;
Vector3 movement = new Vector3(moveHorizontal, moveUp, moveVertical);
transform.Translate(movement * Time.deltaTime * speed);
}
//物理更新w
void FixedUpdate()
{
if (speed == 0) return;
rb.velocity = new Vector3(moveDirection.x, rb.velocity.y, moveDirection.z) + Vector3.up * jumpHeight;
jumpHeight = 0f;//初始化跳跃高度
}
void Jump()
{
jumpHeight = 5f;
}
}
2.相机放在人物头部,转动需要带着人物转,相机转动灵敏度和上下转动角度范围根据具体情况配置。
using UnityEngine;
public class CameraController : MonoBehaviour
{
[Header("鼠标灵敏度")]
public float mouseSensitivity = 4f;
[Header("上下旋转最小角度")]
public float minRotate = -60f;
[Header("上下旋转最大角度")]
public float maxRotate = 60f;
//头部
private Transform head;
private float mouseX = 0f;
private float mouseY = 0f;
private void Awake()
{
//获取相机
head = transform.Find("Main Camera");
}
// Start is called before the first frame update
void Start()
{
}
void Update()
{
//获取左右转动度数
mouseX += Input.GetAxis("Mouse X") * mouseSensitivity;
//获取上下转动度数
mouseY += Input.GetAxis("Mouse Y") * mouseSensitivity;
//上下转动限制范围
mouseY = Mathf.Clamp(mouseY, minRotate, maxRotate);
//控制相机和人物左右转动
Quaternion quaternionX = Quaternion.AngleAxis(mouseX, Vector3.up);
Quaternion quaternionY = Quaternion.AngleAxis(0, Vector3.left);
transform.rotation = quaternionX * quaternionY;
//控制相机上下转动
quaternionY = Quaternion.AngleAxis(mouseY, Vector3.left);
head.rotation = quaternionX * quaternionY;
//人物移动
Player player= GetComponent<Player>();
player.run();
}
}
脚本CameraController和Player直接挂载到人物就可以用了。
3. 文件目录(人物final bowser fly,相机Main Camera)
调整人物和相机的位置文章来源:https://www.toymoban.com/news/detail-763662.html
文章来源地址https://www.toymoban.com/news/detail-763662.html
到了这里,关于Unity实现人物移动、旋转、跳跃的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!