- Home /
Need help getting starting directions within a certain range
I'm trying to get my head wrapped around rotations work. In one respect, there is the rotation that is the spin of an object, but there is another rotation that is what direction the object is facing. It is the latter that I need help with. I have object spawning off screen that I want to come onto the screen. That means depending on which side of the screen they are spawning, they need to only go within a certain range of directions.
I am working in a 3D environment, but I'm making it work as a top-down 2D shooter game. This means that Z+ is "up", Z- is "down", X+ is "right," and X- is "left".
I've done quite a bit of searching online, but unfortunately nothing I've found has helped. I'm wanting to keep my objects moving on the X and Z planes, but again, only within a certain range based on where they are coming from. I have my code already set up to spawn them where they need to be, I just can't figure out this direction issue.
EDIT: I managed to figure it out with Euler by doing this:
spawnRotation = Quaternion.Euler(0, Random.Range(130f, 230f), 0);
And I'd just put the angle range (between 0-360) where I wanted it to come from. In the above case, that is what I used for my angles when my objects spawn at the top of the screen.
$$anonymous$$aybe what you want is Vector3.Angle? It takes 2 positions and returns the angle of the positions. Best way to do for a terrain map is to make a new position with the old position and remove the y axis, so that it only calculates a flat angle. If the angle is less than 90 degrees it will be in front of the object you are comparing to, and if it is greater, so anything greater than 90 would be out of visual range. A quick example..
public bool IsVisible(Vector3 origin, Vector3 target)
{
origin.y = 0;
target.y = 0;
return Vector3.Angle(origin, target) < 90.0f;
}
Should clarify that Vector3.Angle doesn't produce anything sensible when you provide positions, only directions. An "angle" between positions doesn't make geometric sense.
Yeah I don't know what I was thinking, thanks for the correction :)
If you can get it working in one direction, Add the Z rotation by multiple of 90 depending on which side it comes from e.g.
//from bottom.
transform.eulerAngles.z = Random.Range(-45, 45);
//if it is spawned from the top
transform.eulerAngles.z += 180;