- Home /
how to get instantiated object to rotate?
im currently working on a script that creates an object and fires it. i have it set to transform.forward so i know that is should be firing in the right direction. the problem is that even with the rb.addforce (yes ive checked if its finding the rigidbody, it is) its not moving no matter how high i put the speed variable, can anyone help?
public GameObject firePrefab;
public Transform firepoint;//Predetermined spawnpoint
public Animator anim;
public Rigidbody rb;
public float speed;
public GameObject childfire;
public GameObject Player;
private void Start()
{
childfire = gameObject.transform.Find("fire").gameObject;
firePrefab = Resources.Load("fire") as GameObject;
firepoint = gameObject.transform;
anim = gameObject.GetComponent<Animator>();
rb = firePrefab.GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse1))
{
Debug.Log("m1");
StartCoroutine(firetime());
}
else
{
anim.SetBool("Fire",false);
}
}
IEnumerator firetime()
{
anim.SetBool("Fire", true);
childfire.SetActive(false);
yield return new WaitForSeconds(0.4f);
CastFire(firePrefab, firepoint.transform.position, firepoint.transform.rotation);
rb.AddForce(transform.forward * speed * Time.deltaTime);
yield return new WaitForSeconds(0.4f);
childfire.SetActive(true);
}
//"fire"' method
void CastFire(GameObject prefab, Vector3 position, Quaternion rotation)
{
GameObject fireObject = Instantiate(firePrefab, firepoint.position, Quaternion.identity);
}
I guess the problem is that you are adding the force to the RigidBody of the prefab and not to the RigidBody of the instantiated GameObject.
Answer by yoHasse · Aug 03, 2018 at 02:10 PM
@kalsut1 You are currently setting the "rb" variable to the Prefab and not to the instantiated object. You are basically adding force to an object that isn't created in your scene. Make sure to add the force to the instantiated object in your CastFire method.
//"fire"' method
void CastFire(GameObject prefab, Vector3 position, Quaternion rotation)
{
GameObject fireObject = Instantiate(firePrefab, firepoint.position, Quaternion.identity);
//You want to add force to this fireObjects' rigidBody. Not the prefab.
rb = fireObject .GetComponent<Rigidbody>();
}
@yoHasse Thanks! now that i figured that out ive gotten the prefab to move, however can you tell me why even though im using transform.forward my object is still always moving in a set direction?
If you look at the part: rb.AddForce(transform.forward speed Time.deltaTime);
You are basically adding force to it in a forward speed. What your code is say is: "Along this x axis, push the object forward over time."
If you want to rotate then look at the function AddTorque().
Read more about AddTorque HERE And there's a video about it HERE
Please mark as solution if it resolved your issue.