1
\$\begingroup\$

I'm having an issue where I can't seem to rotate my bullet appropriately whenever I spawn one. I currently have a capsule prefab I am testing with. I spawn it with the following code.

        GameObject b = (GameObject)Instantiate(Resources.Load<GameObject>("Prefabs/Bullet"));

I am using the following code to try and orient the bullet so that it lays along the imaginary ray between it's spawn location and the centre of the target.

    void Start() {
    go = InputController.instance.hit.transform.gameObject;
    transform.position = new Vector3(transform.parent.position.x, transform.parent.position.y - 5, transform.parent.position.z);
}

void Update () {
    transform.LookAt(go.transform.position);
    Vector3 rotation = transform.eulerAngles; //THIS IS THE LINE I NEED TO ALTER
    transform.rotation = Quaternion.Euler(rotation);       
    transform.position = Vector3.MoveTowards(transform.position, go.transform.position, SPEED * Time.deltaTime);
    Debug.DrawRay(transform.position, transform.forward * 10000000, Color.red); //DEBUGGING
    Debug.DrawRay(transform.position, transform.up * 1000000, Color.green); //DEBUGGING
}

Essentially the issue I am having is how I can calculate the rotation of the object based on the two I have available.

As you can see the line that I can't seem to calculate is the second line of the Update method, what it needs to do is orient the Vector3.up direction of the object to run along the Vector3 created by linking its position with the target location.

Interestingly the bullet is already laying horizontally but the LookAt method changes its rotation so I just need to fix it but I'm not sure on the math to do that.

\$\endgroup\$
2
\$\begingroup\$

LookAt definition:

 public void LookAt(Transform target, Vector3 worldUp = Vector3.up); 

The default orientation, Vector3.up, it's not correct in your case (that's why the bullet is oriented upwards). Use:

transform.LookAt(go.transform.position, Vector3.right);
\$\endgroup\$
  • \$\begingroup\$ Thanks I don't know why that had to be so hard, just for reference I had to rotate it around x and not y if you want to update the answer in case others come looking for it. \$\endgroup\$ – Scott Mar 2 '15 at 8:52
  • \$\begingroup\$ Please check my updated answer. \$\endgroup\$ – Mihai-Andrei Dinculescu Mar 2 '15 at 8:56
  • \$\begingroup\$ youtube.com/watch?v=CWxKLkJUxbo \$\endgroup\$ – Savlon Mar 2 '15 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.