T
T
tryty2021-11-24 11:51:40
Unity
tryty, 2021-11-24 11:51:40

Rotate character on click movement?

The character moves on click, but there is a problem at short distances - it does not work Flip();.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player : MonoBehaviour {

  public float speed;
  private Vector3 targetPosition;
  private bool isMoving = false;
  private bool facingRight = true;
  
  void Update()
    {
    if(Input.GetMouseButtonDown(0))
    {
      SetTargetPosition();
    }
    
    if(isMoving)
    {
    Move();
    }
    
    if(!facingRight && targetPosition.x > 0.1)
    {
      Flip();
    }
    else if(facingRight && targetPosition.x < 0.1)
    {
    Flip();  
    }
  }
  
  void SetTargetPosition()
  {
    targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    targetPosition.z = transform.position.z;
    
    isMoving = true;
  }
  
  void Move()
  {
    //transform.rotation = Quaternion.LookRotation(Vector3.forward, targetPosition);
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
    
    if(transform.position == targetPosition)
    {
      isMoving = false;
    }
  }
  
  private void Flip()
  {
    facingRight = !facingRight;
    Vector3 Scaler = transform.localScale;
    Scaler.x *= -1;
    transform.localScale = Scaler;
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tryty, 2021-11-24
@tryty

But it dawned on me why I didn’t always rotate targetPosition.x > 0.1, because when I stood by x by 2 and moved by 1, then it worked for me > 0, even though I went in the opposite direction

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question