- Home /
Aiming with the mouse in a 2d shooter, and then shooting to the mouse
So I was wondering how I can use the mouse to aim in my 2d sidescroller and then shoot to where the cursor is. I've looked at some questions asked on this site that are like mine already, but so far none of them have helped. Any help is most appreciated. Thank you all in advance.
Answer by Berenger · May 08, 2012 at 02:45 PM
You can add a box collider in front of the camera then use Physics.Raycast and ScreenPointToRay. Or Plane.Raycast with a Plane( Vector3.back, Vector3.zero ).
Now how exactly would I put that into code? I looked into both, but they don't seem to have good examples of how to use it for ai$$anonymous$$g with the mouse and shooting.
Answer by Piflik · May 08, 2012 at 05:56 PM
I have an invisible plane in my scene that is used to calculate the position of the mouse pointer in the 3D game world:
private var layerMask = 1 << 8; //plane is on layer 8
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), mousPos, Mathf.Infinity, layerMask)){
//lookAt mousPos.point
}
(should be even easier in a top down 2D shooter)
For shooting:
if(Input.GetKey(KeyCode.Mouse0)) {
//shoot
}
I don't exactly get what the plane and layermask are. I'm still pretty new with Unity. Can you explain it a bit more, or give me a link to more information about it?
The layer $$anonymous$$ask is essentially a binary code to say which layers are visible to the ray. 1 << 8 is a 1, shifted left 8 times, so the result is 10000000. This means the 8th layer is visible, all others are not. 10100101 would be layer 8, 6, 3 and 1 are visible, 7, 5, 4 and 2 are invisible. (I omitted leading 0s. The complete code has 32 digits/bits)
The plane is a standard unity plane-object. I disabled the $$anonymous$$esh Renderer Component, so it isn't visible to the camera, and put it on layer 8.
Thank you for explaining that. I have 1 more question... maybe 2 more depending on if I encounter problems. Can you explain how to make it aim to where the cursor is. What I mean is, can you explain the look at code more? Sorry, but I'm very new to program$$anonymous$$g with unity.