2D Object following the cursor without glitchyness at the center
I lack the technical know-how to ask this question in the title...
I have a 2D square that follows the mouse cursor. The red line connects the player and the mouse. I then extend this line for game-play purposes, shown in green.
This isn't relevant, but for clarity, when the player holds right-click, its movement speed slows and the movement continues in its current trajectory, allowing the cursor to freely move around without controlling the player. This will be useful for game play mechanics later on, this isn't relevant to the question.
public class PlayerMechanics : MonoBehaviour
{
Vector3 mousePos;
public float defaultMoveSpeed;
public float slowMultiplyer;
float clampSpeed;
public float smoothTime;
Vector3 smoothVelocity = Vector3.zero;
public float posExtention;
public Vector3 direction;
Vector3 targetPos;
void Start ()
{
}
void FixedUpdate ()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
if (!Input.GetKey(KeyCode.Mouse1))
{
direction = (mousePos - transform.position).normalized;
clampSpeed = defaultMoveSpeed;
}
else
{
clampSpeed = defaultMoveSpeed * slowMultiplyer;
}
targetPos = transform.position + (direction * posExtention);
Debug.DrawLine(transform.position, targetPos, Color.green);
Debug.DrawLine(transform.position, mousePos, Color.red);
transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref smoothVelocity, smoothTime, clampSpeed, Time.deltaTime);
}
}
Now this all works fine, but when the cursor hovers over the player, the direction is constantly changing causing the player to glitch out. I'm really not sure the best way to solve this.
https://gyazo.com/574b1ebaa82299ab4292653a882376b3 https://gyazo.com/4481ceb60dd239daad6483639382ee70
Any advice would be greatly appreciated. Thanks!
Your answer
Follow this Question
Related Questions
Why won't my 2D Sprite Move? 1 Answer
Player Movement Not Always Responding 1 Answer
How can I make the character jump between the boxes? 0 Answers
Homing attack suggestion 0 Answers