Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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);
share|improve this answer
    
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. –  Scott 15 hours ago
    
Please check my updated answer. –  Mihai-Andrei Dinculescu 15 hours ago
    

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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