I currently have a pretty good working prototype of a top-down, “twin-stick” shooter, where the camera is facing downward, and the player is controlled with wasd, and is always facing the mouse.
But all my weapons I have developed so far just shoot raycasts or projectiles (depending on the weapon) from the player, in the direction he is facing. This is great for flat levels, but if I am ever to introduce ledges, ramps, or higher platforms, people would never be able to shoot at people above or below them.
In an ideal solution, I would have it so that if the player was shooting at someone at a higher or lower plane than himself, the bullets/projectile would automatically go up or down to the plane that the enemy was on, otherwise, stay on the plane of the character.
How would I go about pulling that off?
Instead of pointing a 1-dimensional object (line, raycast) in the direction your character is facing, you could use a 2-dimensional object (a plane or significantly flattened cube) extending from the front of your character. I recommend a cube set up something like this:
- scale = 1, 30, 30 or something like that
- positioned so it extends off the front of your character, in the direction of the mouse pointer
- no mesh renderer
- mesh collider changed to a trigger
Then use a few of the cube’s monobehaviour events. OnTriggerEnter() of any enemy: set that enemy as your target. It has to be in front of you but it doesn’t matter if it is above or below. OnTriggerExit() of the enemy: it’s no longer your target, so shoot level. If there are two or more enemies in your line of sight … well, pick one randomly to target. And make sure to keep track of how many enemies are in your line of sight, so if there were 2 and 1 leaves, you can still target the remaining enemy.
Seems like a complicated solution, although it may be the best.
My thoughts:
-Couldn’t you just raycast from the camera through the cursor and have the player aim(raycast to shoot) at the camera’s raycast’s collided position?
-The one problem I could see here is offsetting to shoot at the right spot, ie: Clicking to shoot at an enemy, the raycast might hit the top of the enemy collider, so that’s where the player would aim which is bad, or if you shot in front of the player it would collide with the ground so you’d shoot to low.
-Possible solution - if raycast collides with tagged “Enemy” gameobject, shoot at gameobject.position which would hopefully be the center… and if its anything else, offset up 1meter or so for the average shooting height.
If this made no sense, let me know :P.