I am trying to make a lock-on-target system for a melee combat game. The idea is that when you lock an enemy you switch to a movement system where, if pressing left or right, you rotate around him.
Pressing forward or back will move the player closer or farther from the enemy (de facto increasing or decreasing the radius of the rotation).
I am almost there. I say almost because my character does spirals around the enemy, not circles. The idea is the following:
// Gather the direction of the analog stick.
Vector3 stickDirection = new Vector3 (horizontal, 0f, vertical);
speedOut = stickDirection.magnitude;
// Calculate the relative position player/target and kill the y.
Vector3 lineToTarget = target.position - player.position;
lineToTarget.y = 0f;
// Create a rotation to align with the vector player --> target and apply the rotation to the stick direction.
Quaternion movementRotation = Quaternion.LookRotation(lineToTarget);
Vector3 targetStickDirection = movementRotation * stickDirection;
// Apply speed.
directionOut = targetStickDirection * speedOut;
At this point the direction of the stick vector is relative to the enemy. This direction is used to create the final rotation for the player:
targetRotation = Quaternion.LookRotation (direction, Vector3.up);
Quaternion newRotation = Quaternion.Lerp (player.rotation, targetRotation, speedDirection * Time.deltaTime);
transform.rotation = newRotation;
The speed is also passed to the Animator that simply moves the player forward based on it.
So, to recap:
- The code above is used to define the direction of the stick relative to the targeted enemy.
- The direction used to rotate the player
- The animator pushes the player forward
Result: The player orbits around the enemy. BUT in a spiral! What am I doing wrong?! Or, better, how would you achieve a “Lock on target” system (kinda like Dark Souls)?
Thanks for any effort guys!
[EDIT]
Please refer to the following video that clarifies the situation:
The red line is the relative vector player → target
The green line is the directionOut Vector.
The blue line is the player.forward Vector.
You see that the latter it is pointing slightly outwards. I cannot get why! It should be overlapping the green one!