- Home /
Question by
NerdRageStudios · Jul 15, 2014 at 12:18 PM ·
vector3addforcetorque
How to stop adding torque and force when object collides with collider (or ground)
Hi, I use the following script to ping a coin from a monster when it dies, however, the prefab keeps spinning and moving on the floor.
How can I make it stop one it has collided with something?
using UnityEngine;
using System.Collections;
public class ScriptObjectGoldPickup : MonoBehaviour
{
ScriptPlayerOneManager script;
public GameObject theSound;
private Vector3 torque;
// Use this for initialization
void Start()
{
script = GameObject.Find("PrefabPlayerOne").GetComponent<ScriptPlayerOneManager>();
}
void Awake()
{
torque.x = Random.Range (-200, 200);
torque.y = Random.Range (-200, 200);
torque.z = Random.Range (-200, 200);
constantForce.torque = torque;
rigidbody.AddForce(Vector3.up * Random.Range(2, 5), ForceMode.Impulse);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "PrefabPlayerOne")
{
script.playerInventory.playerOneGoldAmount += 1;
Instantiate(theSound, transform.position, transform.rotation);
Destroy(gameObject);
}
}
}
Thanks in advance for any help :)
Comment
Best Answer
Answer by NerdRageStudios · Jul 15, 2014 at 12:41 PM
Ah, solved it myself with a Boolean :) Finally, I feel like I am learning C# now :)
using UnityEngine;
using System.Collections;
public class ScriptObjectGoldPickup : MonoBehaviour
{
ScriptPlayerOneManager script;
public GameObject theSound;
private Vector3 torque;
private bool collided = false;
// Use this for initialization
void Start()
{
script = GameObject.Find("PrefabPlayerOne").GetComponent<ScriptPlayerOneManager>();
}
void Awake()
{
if (collided == false)
{
torque.x = Random.Range (-200, 200);
torque.y = Random.Range (-200, 200);
torque.z = Random.Range (-200, 200);
constantForce.torque = torque;
rigidbody.AddForce(Vector3.up * Random.Range(5, 10), ForceMode.Impulse);
}
}
// Update is called once per frame
void Update()
{
if (collided == true)
{
torque.x = 0;
torque.y = 0;
torque.z = 0;
constantForce.torque = torque;
}
}
private void OnCollisionEnter(Collision collision)
{
collided = true;
if (collision.gameObject.name == "PrefabPlayerOne")
{
script.playerInventory.playerOneGoldAmount += 1;
Instantiate(theSound, transform.position, transform.rotation);
Destroy(gameObject);
}
}
}