How do you instantiate an object at the tip of a rotating object?
So basically I'm trying to make a simple space shooter similar to asteroids. All I want to do is instantiate the bullet at the end of the ship so it shoots our the tip but for some reason the code I implemented wont work as the bullet still shooting from the center of the ship which makes it look awkward in essence.
Movement Code
Rigidbody2D body;
float maxSpeed = 300f;
void Start(){
body = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
if (body.velocity.magnitude > maxSpeed) {
body.velocity = body.velocity.normalized * maxSpeed;
}
}
void Update () {
Quaternion rot = transform.rotation;
float z = rot.eulerAngles.z;
if(Input.GetKey(KeyCode.A)){
z += maxSpeed / 100;
}
if(Input.GetKey(KeyCode.D)){
z -= maxSpeed / 100;
}
rot = Quaternion.Euler (0, 0, z);
transform.rotation = rot;
if (Input.GetKey (KeyCode.W)) {
body.AddForce (transform.up * .03f);
}
}
Shooting Code
public Vector3 bulletOffset = new Vector3(0, 3f, 0);
public GameObject projectile;
void Update () {
Vector3 offset = transform.rotation * bulletOffset;
if (Input.GetKeyDown (KeyCode.Space)) {
Instantiate (projectile, transform.position + offset, transform.rotation);
}
}
Answer by BackslashOllie · Apr 27, 2017 at 10:34 AM
Personally, I would add a child GameObject to your ship, place it at where you would like the bullets to fire from and then reference it's Transform in your shooting code.
For example
public Transform shootingPoint; //Set this to child object in inspector
void Update () {
if (Input.GetKeyDown (KeyCode.Space))
Instantiate (projectile,
shootingPoint.position,
shootingPoint.rotation);
}
This is a very simple work around and works like a charm. THAN$$anonymous$$ YOU!
Your answer
Follow this Question
Related Questions
Enemy Ai Rotation not working properly 0 Answers
I can't seem to rotate my character depending on what side he is running to (2D sidescroller) 0 Answers
How to make a 2D rigidbody vertically when input is via the gyroscope 0 Answers
[Normal Map on 2D Graphics] I NEED HELP! 0 Answers
How to Transform.Rotate Around with the rotation of the controller right stick 0 Answers