- Edited
Given that the player holds the gun at a gun handle, but the direction from which the bullet flies from is located at the gun's barrel (direction vector) - how do I find the angle which the gun should be rotated to, in order for the bullet to fly straight at the enemy, i.e. in order for the gun to point straight at the enemy?
here is the example of the scene:
where:
- is the pivot point/rotation origin
- the barrel direction vector, origin of the bullet
- the enemy
if I were to simplify the drawing it would look like this. Is what I have:
is what I want to achieve
I am using godot 4.0 stable
and a C#
but answers in any language will help.. Here is the code I have, but it does not work..
public override void _Process(double delta) {
Vector2 pivotPoint = GlobalPosition;
var marker2DFrom = GetNode<Marker2D>("Marker2DFrom");
var marker2DTo = GetNode<Marker2D>("Marker2DTo");
Vector2 directionVector = (marker2DTo.GlobalPosition - marker2DFrom.GlobalPosition);
var enemy = GetNode<Node2D>("Enemy");
Vector2 targetPoint = enemy.GlobalPosition;
Vector2 pivotToPoint = targetPoint - pivotPoint;
float dot = directionVector.Dot(pivotToPoint);
float cross = directionVector.Cross(pivotToPoint);
float radians = Mathf.Atan2(cross, dot);
float degrees = radians * (180f / Mathf.Pi);
GlobalRotationDegrees = GlobalRotationDegrees + degrees;
}
this produces the exact same (wrong) result at simply using LookAt(enemy.GlobalPosition);
- it works, but the barrel vector is not pointing at the enemy..