- Home /
Un-normalize direction
So I have this line of code for when my enemies fire a shot.
Rigidbody2D Shot;
Shot = Instantiate (ProjectileTest, target.position, Quaternion.Euler (Vector3.forward)) as Rigidbody2D;
Shot.velocity = transform.TransformDirection (new Vector3(Random.Range (-firingArc,firingArc),0,1) * bulletspeed);
Shot.transform.Rotate (Vector3.forward);
The code works exactly the way it should. There's no problems here. Bulletspeed determines how quickly the bullet flies while firingArc gives me control over the bullet spread for when my enemy is a particularly bad shot, for example. target is the bullet spawn position.
However my control over which direction the bullet spawns is lacking, in my opinion. I can only input a number -1 to 1, when I would prefer to use regular Degrees to give me control over my bullet spread, in particular. Are there options for this?
Answer by Bunny83 · Feb 19, 2016 at 06:44 AM
Well, if you want to use an angle instead of a vector offset you have to use Sin and Cos.
float angle = Random.Range (-firingArc,firingArc) * Mathf.Deg2Rad;
Shot.velocity = transform.TransformDirection (new Vector3(Mathf.Sin(angle),0,Mathf.Cos(angle)) * bulletspeed);
In this case "firingArc" should be in degree. So a value of 10 will result in a 20 degree sector since you go left and right.
I'm just a bit confused. You seem to use the x and z component but you use 2D physics. 2D in Unity is usually the x-y plane. Is it a top down game?
Just saw another thing that doesn't make much sense:
Quaternion.Euler (Vector3.forward)
Quaternion.Euler expects eulerangles in degree. You pass the constant value (0,0,1) so the object will appear almost like not rotated at all (just 1 degree around the y axis).
It works! Thanks a lot.
To answer your questions yes it is a top-down game. using the X-Z plane is a matter of personal preference as i'd rather not have to worry about things like gravity when I make a rigidbody2D.
As for the Quaternion.Euler, I couldn't tell you. $$anonymous$$ight have been useful once but is now just some artifact-code that needs to be there but isn't really hurting anything.