Unity移动物体时,当接近目的地时自动吸附

本文介绍了一种在Unity中使物体移动到指定位置的方法,使用了Vector3和Quaternion来定义目标位置和旋转,通过比较当前位置与目标位置的距离,当距离小于设定阈值时,物体将瞬移到目标位置并调整其旋转。

移动的物体是LuoGan04

目标位置有local position 和旋转确定。Rotation就四元素,其可以把面板调为debug时,再查看。

但这样写会比较麻烦,一个改进的方案是把目的地的位置调好后,将其做成预制体,这时可以面板上把这个零件删除。然后在脚本中同样申请一个public变量,把目的地的预制体赋给它,在通过transform获取其position和rotation这样会比上面第一种方案可能好一点。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoA : MonoBehaviour {


	GameObject LuoGan04;
	Vector3 LuoGan04Aim = new Vector3(37.71f, 4.74f, -22.0f);
	Quaternion LuoGan04Qua = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);


	// Use this for initialization
	void Start () {
		LuoGan04 = GameObject.Find ("04_LuoGan");
		print (LuoGan04.name );

	}
	
	// Update is called once per frame
	void Update () {

		print ("000000000p" + LuoGan04.transform.localPosition);
		print ("1111111111111p" +LuoGan04Aim);

		print ("2222222222222p" + (LuoGan04.transform.localPosition - LuoGan04Aim).magnitude );
		if (Mathf.Sqrt((LuoGan04.transform.localPosition - LuoGan04Aim).magnitude) < 1.5) {
			LuoGan04.transform.localPosition = LuoGan04Aim;
			LuoGan04.transform.localRotation = LuoGan04Qua;

		}



		
	}
}

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值