在进行unity开发时,使用character control组建的实例,人物平滑的转向,然后朝着正前方移动。
这里实现三个效果,鼠标点击物体向正前方移动、awsd控制朝向、物体始终朝向目标。
1)鼠标点击目标移动
if (Input.GetMouseButton (0))
{
transform.Translate (Vector3.forward * Time.deltaTime * moveSpeed, Space.Self);
}
2)awsd控制朝向
//获取控制的方向, 上下左右,
float KeyVertical = Input.GetAxis (“Vertical”);
float KeyHorizontal = Input.GetAxis (“Horizontal”);
Vector3 newDir = new Vector3 (KeyHorizontal, 0, KeyVertical).normalized;
transform.forward = Vector3.Lerp (transform.forward, newDir, RotateSpeed);
3)物体始终朝向目标
Vector3 rotateVector = Target.position - ThisTransform.position;
Quaternion newRotation = Quaternion.LookRotation (rotateVector);
ThisTransform.rotation = Quaternion.RotateTowards (ThisTransform.rotation, newRotation, RotateSpeed * Time.deltaTime);
具体在工程中的应用,新建sphere,添加脚本:
using UnityEngine;
using System.Collections;
public class MoveByADSW : MonoBehaviour {
//人物移动速度
public int moveSpeed = 2;
public float RotateSpeed = 0.2f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//获取控制的方向, 上下左右,
float KeyVertical = Input.GetAxis (“Vertical”);
float KeyHorizontal = Input.GetAxis (“Horizontal”);
Vector3 newDir = new Vector3 (KeyHorizontal, 0, KeyVertical).normalized;
transform.forward = Vector3.Lerp (transform.forward, newDir, RotateSpeed);
if (Input.GetMouseButton (0)) {
transform.Translate (Vector3.forward * Time.deltaTime * moveSpeed, Space.Self);
}
}
}
新建cube,添加脚本:
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class LookAT : MonoBehaviour {
//cached transform
private Transform ThisTransform = null;
//Target to look at
public Transform Target = null;
//Roate speed
public float RotateSpeed = 100f;
void Awake()
{
ThisTransform = GetComponent ();
}
// Use this for initialization
void Start () {
StartCoroutine ((TrackRotation(Target)));
}
IEnumerator TrackRotation(Transform Target)
{
while (true)
{
if (ThisTransform != null && Target != null) {
Vector3 rotateVector = Target.position - ThisTransform.position;
Quaternion newRotation = Quaternion.LookRotation (rotateVector);
ThisTransform.rotation = Quaternion.RotateTowards (ThisTransform.rotation, newRotation, RotateSpeed * Time.deltaTime);
}
yield return null;
}
}
void OnDrawGizmos()
{
Gizmos.DrawLine (ThisTransform.position, ThisTransform.forward.normalized * 5f);
}
}
作者:夫人的泡泡鱼
来源:CSDN
原文:https://blog.csdn.net/zqckzqck/article/details/73172479
版权声明:本文为博主原创文章,转载请附上博文链接!