Hi All,
I have a 2D top down game where the character needs to follow the mouse cursor, but also strafe in world space.
I have managed to do either one of these things, but putting the two together is causing some headaches.
I’ve almost managed to get it working but I’m stuck with how the CharacterController.SimpleMove uses its argument in world space.
Because the character follows the mouse, I need to add relative movement based on which way the character is facing.
//Code C#
void Update () {
cControl = GetComponent<CharacterController>();
lookPoint = GameCore.lookTarget; //static val, contains mouse position in world space
lookPoint.y = transform.position.y; //remove any y drift from distance
transform.LookAt(lookPoint);
calMov();
}
void calMov(){
float xAxis = (Input.GetAxisRaw("Horizontal") * walkSpeed);
float zAxis = (Input.GetAxisRaw("Vertical") * walkSpeed);
float mouseDist = Vector3.Distance(transform.position, lookPoint);
if(Input.GetMouseButton(1)){
if(mouseDist > 4){mouseDist = runSpeed;}
else{mouseDist = walkSpeed;}
}
else{mouseDist = 0;}
Vector3 movement = new Vector3(xAxis, 0, zAxis);
Vector3 relForward = new Vector3 (0,0,mouseDist);
relForward = transform.InverseTransformDirection(relForward); //Problem here. movement += relForward;
movement = Vector3.ClampMagnitude(movement, runSpeed);
cControl.SimpleMove(movement);
}
I’m currently using InverseTransformDirection, but while this makes the character follow when parallel to the world Z axis. It inverts and moves back from the mouse when facing world X.
I’ve tried more solutions to this than I care to count and none produce the desired result. Effectively what I am trying to achieve is the equivalent of RigidBody.AddRelativeForce(new Vector3(0,0,forward)); This gives the desired moving toward mouse, but then I run into a whole heap of problems controlling speed.
Ideally I’d like to get to the following:
-
The character to face and run after the mouse cursor.
-
Strafe in world space via WASD regardless of direction character is facing.
-
Clamp the velocity of the character so the total magnitude never exceeds runSpeed.
I’ve seen some examples of rotating a Vector3 to face a direction, but all I can get out of that approach is compiler errors.
Help with any of these goals would be greatly appreciated.