控制物体移动
直接上代码(改脚本挂载到游戏物体上)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
private Vector3 move; //移动方向
private float movespeed = 3f; //移动速度
private float H, V;
// Start is called before the first frame update
void Start()
{
move = new Vector3(0, 0, 0);
}
// Update is called once per frame
void Update()
{
//获取按键信息
H = Input.GetAxis("Horizontal");
V = Input.GetAxis("Vertical");
move.x = H;
move.z = V;
//获取摄像机朝向
float y = Camera.main.transform.rotation.eulerAngles.y;
move = Quaternion.Euler(0, y, 0) * move;
if (H != 0 || V != 0)
{
//使物体移动
transform.Translate(move * Time.deltaTime * movespeed, Space.World);
//这一步是使物体移动时始终面向前方
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, y, 0), 0.05f);
}
}
}