转获取控制朝向方位信息

在进行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
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值