Raycast in 2.5D for bullet targeting

EDIT:Solved! Thank you so much for your help!


I have a side scrolling game set up with the 2d gameplay tutorial on the unity website.

In my game, I want the player to be able to shoot along the X and Y axis in the direction of the cursor.

The camera's distance isnt a fixed distance from the character, and the character isnt always in the center of the screen.

I want to use raycasting with a ray from the camera to the 2d plane and then a ray from the characters gun to the end of the other ray. Then, if there is a collision, apply the damage and particles etc. to make it look like the weapon was fired.

This is all very confusing to me. I cant figure out how to read the coordinates of the ray shot from the camera to the 2d plane.

Hello

static var LOOKING_AT;
function Update () 
{
var mousex = Input.mousePosition.x;
var mousey = Input.mousePosition.y;
        //ray from camera to world point at cursor
var ray = camera.main.ScreenPointToRay (Vector3(mousex,mousey,0));
Debug.DrawRay (ray.origin, ray.direction * 15, Color.yellow);

//What is the loc at the end of the ray?
LOOKING_AT = ray.direction * 15;
//15 is the current distance from the camera. I need this to be dynamic.

LOOKING_AT.z=0;
//set to 0 because its on a 2d plane
print (LOOKING_AT);

}

to make it simple, could I just have an invisible object that always follows the cursor, and then shoot a ray from the character to that object? Once I figure this out, I think I can use the tutorials Ive scavenged from all over the web to make the rest of this process easier.

Thanks for helping.

One way is to use `Camera.cameraToWorldMatrix` to convert from camera space to world space, the z component here is the -distance from the camera.

Another (probably easier) way you could do it is to make a plane-collider at the distance the bullet is supposed to shoot, put this in a separate layer and use `Camera.ScreenPointToRay` and `Physics.Raycast` (only checking the layer the plane collider is in) to find the point where the screen ray intersects the bullet plane.

Even easier than `cameraToWorldMatrix` is to use `Camera.ScreenToWorldPoint`, as you don't have to scale the mouse position to -1..1 range (and then you have to take into account aspect ratio).

var gun : Transform;

function Update () {
    var gunPosition : Vector3 = gun.position;

    // distance calculation assumes camera has 0, 0, 0 rotation
    var distanceFromCamera : float = gunPosition.z - camera.main.transform.position.z;

    var screenPos : Vector3 = Input.mousePosition;
    screenPos.z = distanceFromCamera;

    // calculate where in the game-plane the bullet must go to
    var worldPos : Vector3 = Camera.main.ScreenToWorldPoint(screenPos);

    // calculate bullet direction...
    var dir : Vector3 = (worldPos - gunPosition).normalized;

    // ... (instantiate, rotate and set direction of bullet)
}