第一种办法使用方向向量的办法:
using UnityEngine;
using System.Collections;
//本案例采用向量的方法
public class test : MonoBehaviour {
public GameObject target; //目标物体
private Vector3 xPos;
float shuLv = 0.1f; //控制物体运动的速率
bool aa = false;
// Use this for initialization
public Vector3 fx; //
void Start () {
fx = target.transform.position - transform.position;
fx = Vector3.Normalize(fx); //单位为1 的方向向量
}
// Update is called once per frame
void Update () {
//鼠标左键按下去开始运动
if (aa)
{
// xPos - transform.position = fx*shuLv; 箭头-箭尾
xPos = fx*shuLv + transform.position;
transform.position = xPos;
if (Vector3.Distance(transform.position, target.transform.position)<0.1)
{
aa = false; //停止运动
}
}
if (Input.GetMouseButtonDown(0))
{
aa = true;
}
}
}
第二种办法:目标约束+Translate
注意Translate ,如果第四个参数不设置,则默认参考的是物体的自身坐标
using UnityEngine;
using System.Collections;
//本案例采用向量的方法
public class test : MonoBehaviour {
public GameObject target;
float shuLv = 0.1f; //控制物体运动的速率
bool aa = false;
void Start () {
}
// Update is called once per frame
void Update () {
//鼠标左键按下去开始运动
if (aa)
{
transform.Translate(0, 0, 1*shuLv);
if (Vector3.Distance(transform.position, target.transform.position)<0.1f)
{
aa = false;
}
}
if (Input.GetMouseButtonDown(0))
{
transform.LookAt(target.transform.position); //目标约束
aa = true;
}
}
}
第三种办法: 使用A*寻路插件
FR:海涛高软(Hunk Xu)