unity中关于物体的旋转和朝向控制

来源:互联网 发布:浏览器 网络连接错误 编辑:程序博客网 时间:2024/05/22 12:09

在进行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<Transform> ();
}
// 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);
}


}