注意:您不需要使用刚体的功能。 如果您想要:Rigidbody.MovePosition(Vector3 position),您可以使用它。
首先检查不可见游戏对象的刚体IsKinematic
字段true
。或者将其删除。之后,您可以更改shouldMove = false,以便它不会进入if语句中。
bool shouldMove = true;
// get key up and the ring will move upwards
if (Input.GetKey (KeyCode.UpArrow)&&shouldMove) ///Check shouldMove
{
transform.position += Vector3.up * speed * Time.deltaTime;
}
// get key down and the ring will move downwards
if (Input.GetKey (KeyCode.DownArrow)&&shouldMove) ///Check shouldMove
{
transform.position += Vector3.down * speed * Time.deltaTime;
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject.name == "Sphere") {
Debug.Log ("Hit Sphere");
shouldMove = false; ///Change shouldMove
}
}
如果您希望一个不可见的物体不会移动,您可以将碰撞器的isTrigger
字段设置为true
。因此,您需要将OnCollisionEnter更改为OnTriggerEnter(Collider other)。
void OnTriggerEnter(Collider other) {
if (other.gameObject.name == "Sphere") {
Debug.Log ("Hit Sphere");
shouldMove = false;
}
}
如果你的戒指需要推动一些物体(不需要推动看不见的物体,但需要推动其他物体),你可以创建新的脚本并将其添加到看不见的物体中。(因此,请检查看不见的物体Collider
IsTrigger
字段
true
。)然后在编辑器中将你的戒指拖放到新的脚本RingController位置以添加引用。
PS:下面的代码中
YourRingControllScript
需要更改为你实际的Ring Controller脚本名称。
public YourRingControllScript ringController;
void OnTriggerEnter(Collider other) {
if (other.gameObject.name == "Sphere") {
Debug.Log ("Hit Sphere");
ringController.shouldMove = false;
}
}
如果您的不可见对象在运行时实例化,那么您需要知道RingControllers持有者的GameObject。您可以使用
GameObject.Find("GameObjectName")找到GameObject。
您可以添加Start()方法:
void Start(){
ringController = GameObject.Find("RingControllerGameObject").
GetComponent<YourRingControllScript>() as YourRingControllScript; //I think you don't need to add as YourRingControllScript if there is a problem without it you can add.
}
speed
设置为 0,并将isKinematic
设置为false
。 - Paweł Mareckirigidbody
,应考虑使用Rigidbody.AddForce
或Rigidbody.velocity
而不是更改transform.position
。当您使用碰撞器和刚体时,最好使用物理组件。然后我编写的设置应该可以工作,但不必将isKinematic
设置为false
。 - Paweł Marecki