Quantcast
Channel: Latest Questions by Eux86
Viewing all articles
Browse latest Browse all 26

How to rotate a gun in the right way to anticipate the trajectory of a moving object

$
0
0

I'm trying to create a gun that fires to a moving object, anticipating its future position. To do so, I calculate the horizontal and the vertical angles that the gun has to rotate to anticipate the target's movement. The problem comes when i try to rotate the gun. If I use methods like transform.rotate or transform.rotation = Quaternion.euler .. the rotation is not instant and the projectiles fired by the gun don't intercept the target. If i use the metod transfor.rotation = Quaternion.FromToRotation, the gun starts rotating instantly in the right position, then back in another position that, for me, has no sense.

The only solution I found is to:

create an empty GameObject

GameObject go = new GameObject("go");

set its position to the coordinates calculated from the horizontal and the vertical angle

Vector3 coords = Vector3( Mathf.Sin(horizontalAngle), Mathf.Sin(VerticalAngle), Mathf.Cos(HorizontalAngle));
go.transform.position = gun.transform.InverseTransformPoint(coords);

make the gun point to this empty GameObject using transform.LookAt.

gun.transform.LookAt(go.transform.position);

The problem is that all this runs only if the target is moving only horizontally (on the x,z plane) or vertically (on the y,z plane). Note that if the target moves only horizontally, the verticalAngle is 0, while if it moves only vertically the horizontalAngle is 0. If I move the target in both planes the gun goes crazy.

I tried to understand where the problem is, but I can not.

PS: I'm not posting the whole source code just to avoid confusing this message, but if anyone needs it to understand the situation more, I can write it.

Thanks in advance to anyone able to resolve this mess!


Viewing all articles
Browse latest Browse all 26

Trending Articles