using UnityEngine;
using System.Collections;
//获得目标位置的代码
public class Target : MonoBehaviour {
public Transform targetMatker;
void Start() { }
void Update()
{
int button = 0;
if (Input.GetMouseButtonDown(button))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
<span style="white-space:pre"> </span>//移动到鼠标指定的位置后停止
if (Physics.Raycast(ray.origin, ray.direction, out hitInfo))
{
Vector3 targetPosition = hitInfo.point;
targetMatker.position = targetPosition;
}
}
}
}
using UnityEngine;
using System.Collections;
//要控制移动的物体的代码
public class PlayerTank : MonoBehaviour {
public Transform targetTransform;
private float movementSpeed, rotSpeed;
void Start()
{
movementSpeed = 10.0f;
rotSpeed = 2.0f;
}
void Update()
{
//接近要到达的目标指定位置后就停止
if (Vector3.Distance(transform.position, targetTransform.position) < 5.0f)
return;
//实时计算要到达的目标位置与当前位置的距离
Vector3 tarPos = targetTransform.position;
tarPos.y = this.transform.position.y;
Vector3 dirRot = tarPos - transform.position;
//创建一个四元数指向当前位置与目标位置的角度
Quaternion tarRot = Quaternion.LookRotation(dirRot);
//当旋转和移动的时候插入一个值
transform.rotation = Quaternion.Slerp(transform.rotation, tarRot, rotSpeed * Time.deltaTime);
transform.Translate(new Vector3(0, 0, movementSpeed * Time.deltaTime));
}