Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Top-down 2D game. Player getting flipped when it approaches mouse. Please Help!

Discussion in 'Scripting' started by Red_Kay, Nov 5, 2015.

  1. Red_Kay

    Red_Kay

    Joined:
    Aug 14, 2015
    Posts:
    94
    Hello,

    I am making a top-down arcade 2d game in which the player's rotation in based on the mouse position(so player looks at mouse all the time) and move towards mouse upon any axes input. Now if the mouse is not moved and if the player gets to the mouse position it flips. I don't want this to happen and I don't even want my gamers to move mouse all the time as it will distract them from the objective of the game.

    Code here ->

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovementController : MonoBehaviour {
    5.  
    6.     public float speed;
    7.     public float stamina;
    8.     public float force;
    9.  
    10.     Rigidbody2D rb;
    11.  
    12.     void Awake()
    13.     {
    14.         rb = gameObject.GetComponent <Rigidbody2D>();
    15.     }
    16.  
    17.     void FixedUpdate()
    18.     {
    19.         //float h = Input.GetAxis("Horizontal");
    20.         float v = Input.GetAxis("Vertical");
    21.      
    22.         Vector3 verticalMovement = -transform.up * v;
    23.         Vector2 velocity = transform.position + verticalMovement;
    24.         transform.position = Vector3.Lerp(transform.position, velocity, speed * Time.deltaTime);
    25.        
    26.         LookAtMouse();
    27.     }
    28.  
    29.     void LookAtMouse()
    30.     {
    31.         Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    32.        
    33.         float dist = Vector3.Distance(transform.position, mousePosition);
    34.         Vector3 direction = mousePosition - transform.position;
    35.         direction.Normalize();
    36.         float rotZ = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    37.         transform.rotation = Quaternion.Euler(0f, 0f, rotZ + 90);
    38.     }
    39. }
    Please help!
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    Try setting the localEuler instead of the rotation. Quaternions are a strange thing. Also, I don't think normalizing is needed.