2D Click to Move Facing Left & Right

I am making a 2D click to move project but with only a character sprite facing left and right.

I am using a code that I got from “http://unity.grogansoft.com/move-player-to-clicktouch-position/” for the click to move part. (Any better click to move code suggestions would be highly appreciated)

My problem now is how do I code my character facing LEFT when I click on it’s left side and RIGHT when I click on it’s right side?

hi assuming you are using the code from the tutorial you linked this is a possible solution

using UnityEngine;
public class MoveToClickInput : MonoBehaviour
{
[SerializeField] Transform target;
float speed = 6f;
Vector2 targetPos;
private void Start()
{
    targetPos = transform.position;
}
void Update ()
{
    if(Input.GetMouseButtonDown(0))
    {
        targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
        target.position = targetPos;
    }
    if((Vector2)transform.position != targetPos)
    {
       transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
    }
    if((targetPos.x >= transform.position.x)
    {
         transform.localScale = new Vector3(1,1,1); // replace with whatever normal scale you want
    }
    else
    {
         transform.localScale = new Vector3(-1,1,1); // replace with whatever normal scale you want
     }
}
}

I haven’t tested this code however it should just flip the direction your sprite is facing, hope it helps.

1 Like

It works great but

3493690--278261--ezgif.com-video-to-gif.gif

If I click on the left and it stops moving the sprite flips to the right

If you put the last if statement within the the first one after line “target.position = targetPos;” it should only change direction when you click the mouse

2 Likes

WOHOO!! THANK YOOOOOU SOOOO MUCH! IT WORKS!

using UnityEngine;
public class ClickToMove2: MonoBehaviour
{
    [SerializeField] Transform target;
    public float speed = 6f;
    Vector2 targetPos;

    private void Start()
    {
        targetPos = transform.position;
    }
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
            if ((targetPos.x >= transform.position.x))
            {
                transform.localScale = new Vector2(0.3f, 0.3f); // replace with whatever normal scale you want
            }
            else
            {
                transform.localScale = new Vector2(-0.3f, 0.3f); // replace with whatever normal scale you want
            }
            target.position = targetPos;
        }
        if ((Vector2)transform.position != targetPos)
        {
            transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
        }      
    }
}

3494621--278373--green triangle.gif

Thank you so much N-Murray :smile::smile::smile:

1 Like

Glad I could help

2 Likes