ARG.
Alright. It looks so easy, but its not. Not for me anyway. So what I’m doing is setting up a player controller that you move with your mind your mouse.
Step 1: Getting a controller to follow an object:
I used the basic FPS controller as a starting point. Rather than constructing the movement direction vector from the mouse axes, I simply told it to use the position of a game object. Conditional’d that so that it doesn’t fire unless there’s a target. I had to pussyfoot around turning the controller, since I want the camera to be static for the most part, and turning the camera with camera-space controls makes the game control weird.
Step 2: Raycast screenspace to collider:
In the old version I figured out how to shoot a ray from mouse position in screen space to collisions on world space. I also figured out how to use a Layermask to check what the ray hit. Now the system looks to see if you hit something in the Enemy layer first, then checks to see if you hit anything in the Walkable layer if you didn’t. Then, if we have a target that isn’t an enemy, we move our waypoint to the position of the raycast hit in world space. If we hit an enemy, we just make him the target. If we didn’t already have a waypoint target, we make a new one at the hit point.
Step 3: Give the target to the graphics object:
Since the player controller (the deal that actually takes input) never rotates, and only moves to specific points without turning, we need something to rotate the character art. So I made a game object that holds the art and directional stuff (such as attack areas etc), parented it to the controller, and turned that. I setup the controller to broadcast the target to all children so that I can get the target on any given weapon or animation or anything. Then I smoothly interpolate the rotation of the graphics object towards the player’s target.
Most of this is in Fixed Update, so it runs pretty smooth now, with no jitteryness or anything. Pretty sweet. I can now setup my level art so that there are parts that are Walkable and parts that aren’t and the player can’t walk off the map. Whee!!
Edit:
Ok, some other fixes to help with targeting:
When raycasting, we do it in two steps, first to check if its an enemy (so that we can target a mobile game object) and then we check to see if we hit some walkable ground. Now, I added in a check to see if we already have a target that ISN’T an enemy and if we do, we destroy that one. This is because it appeared possible to click off the enemy and back on rapidly and leave a bunch of instantiated targets lying around. I also added in a kill timer on the spanwed targets so that they go away if it takes too long to get there. We are ready for melee combat, baby.












