控制物体移动
直接上代码(改脚本挂载到游戏物体上)文章来源:https://www.toymoban.com/news/detail-612759.html
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);
}
}
}
控制摄像机移动的代码
第三人称摄像机移动文章来源地址https://www.toymoban.com/news/detail-612759.html
到了这里,关于Unity3D 控制物体移动且自动旋转的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!