Hi. I have a scene with a 3D character with a bow that is supposed to shoot at the cursor, but located in a 2D environment, like the picture below, however I’m unable to find such code. I know how to make 2D characters shoot, and I also know how to make 3D characters shoot, but for this specific situation, both approaches make the arrow go off when shooting diagonally.
What could be a solution for this problem?
To help troubleshoot this problem your actual code would probably help ;).
However, if your 2d plane is flat you could use the following extension method. It shoots a ray through the mouse position and calculates the intersection with a “virtual” plane. Just place the plane at the height of the terrain and it should give you a proper position to shoot your projectile towards.
public static class ExtensionMethods_Camera
{
private static Plane xzPlane = new Plane(Vector3.up, Vector3.zero);
public static Vector3 MouseOnPlane(this Camera camera)
{// calculates the intersection of a ray through the mouse pointer with a static x/z plane for example for movement etc, source: http://unifycommunity.com/wiki/index.php?title=Click_To_Move
Ray mouseray = camera.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (xzPlane.Raycast(mouseray, out hitdist))
{// check for the intersection point between ray and plane
return mouseray.GetPoint(hitdist);
}
if( hitdist < -1.0f )
{// when point is "behind" plane (hitdist != zero, fe for far away orthographic camera) simply switch sign https://docs.unity3d.com/ScriptReference/Plane.Raycast.html
return mouseray.GetPoint( -hitdist );
}
Debug.Log ( "ExtensionMethods_Camera.MouseOnPlane: plane is behind camera or ray is parallel to plane! " + hitdist); // both are parallel or plane is behind camera so write a log and return zero vector
return Vector3.zero;
}
}
[code]