- Home /
shoot cannon in the direction barrel is facing
I am teaching myself unity 3d 4.3 so i can create 2D game. As a practice i am writing scorched earth. It is 2D and I rotate the gun barrel, around Z-axis. Lets say it is pointing to right, up 45 degree. Now I created a bullet as child of the barrel. I have code
GameObject newBullet = (GameObject)Instantiate(originalBullet, originalBullet.transform.position, originalBullet.transform.rotation);
newBullet.rigidbody2D.AddForce(new Vector2(1,1) * 250);
Original bullet is placed right in front of the barrel and i clone it. I am having problem with AddForce. Vector2(1,1) is hardcoded to 45 world-degree, but how do I get the direction of the barrel in relation to the world?
Also, is there a good example i can look at it for writing tank shooting game?
Thanks
Answer by NivF · Jan 24, 2014 at 10:53 AM
You should look at the barrel's transform to know it's direction. Depending on how you setup the barrel object it can be either transform.forward, transform.up or transform.right
If you need a Vector2 type then code should look something like:
Vector2 vBarrelDir = new Vector2(transform.up.x,transform.up.y);
newBullet.rigidbody2D.AddForce(vBarrelDir * 250f);
thanks that did it. I still don't understand why it works. per doc, transform.up is green axis, which in my case Y-axis. why is getting .x and .y of y-axis give the direction i want? I believe the better question is, how do i tell which direction the barrel is facing? Is it usually z direction? in that case, shouldn't i have used transform.forward?
Yes, transform.forward would make more sense - but you have to realize unity can't really tell which direction is "forward" on any given mesh ... it's just a fancy name for the object's Z-Axis.
It really depends how your local coordinates are setup in the mesh. When you select your barrel object, you can see it's local coordinate system with the 3 colored arrows as the principal axes of that coordinate system.
If you are the one who made the model (in 3DS-$$anonymous$$ax/$$anonymous$$aya/Blender) you can easily rotate the object so it aligns with the Z-Axis. But it really is not required. There may be some unity scripts that can do that as well ...