unity3d如何控制一个物体移动到指定位置并且立刻停下来

2025-01-03 02:05:47
推荐回答(2个)
回答1:

public class PlayerMove : MonoBehaviour
{
public float speed = 5f; //移动时的速度
private Vector3 Player_dir; //主角的坐标

void Update ()
{
Player_dir.x = -Input.GetAxis("Horizontal") * speed * Time.deltaTime; //移动的X数据
Player_dir.z = -Input.GetAxis("Vertical") * speed * Time.deltaTime; //移动的Z数据
this.transform.Translate(Player_dir.x, 0, Player_dir.z); //移动的距离
Player_dir = this.GetComponent().position; //用来获取当前主角的坐标
Exceed(); //检测是否超出函数
}

void Exceed () //自定义超出函数
{
if (this.transform.position.x > 45) //检测当前主角的X正半轴
{
this.transform.position = new Vector3(45, Player_dir.y, Player_dir.z);
}
else if (this.transform.position.x < -45) //检测当前主角的X负半轴
{
this.transform.position = new Vector3(-45, Player_dir.y, Player_dir.z);
}
else if (this.transform.position.z < -45) //检测当前主角的Z负半轴
{
this.transform.position = new Vector3(Player_dir.x, Player_dir.y, -45);
}
else if (this.transform.position.z > 45) //检测当前主角的Z正半轴
{
this.transform.position = new Vector3(Player_dir.x, Player_dir.y, 45);
}
}
/*注:如果超出对它做出处理,重新指定坐标且这个坐标只能在四象轴范围内。*/
}

回答2:

知道制定位置的坐标,判断当坐标临界制定坐标位置,让物体等于这个坐标向量。