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. Dismiss Notice

how we can move character in fixed rotation

Discussion in '2D' started by bhae, May 17, 2018.

  1. bhae

    bhae

    Joined:
    May 6, 2018
    Posts:
    55
    how we can move character in fixed rotation through 2d script
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    Do you mean that the character should rotate around a center, or do you mean that the character itself should rotate?
     
  3. cardcastleusa

    cardcastleusa

    Joined:
    Mar 20, 2018
    Posts:
    9
    If you want to move a character like in a platform game. You need to add a Rigidbody2D and a BoxCollider2d to your game Object. This will make it so it will be able to apply forces to the object.
    Code (CSharp):
    1.  
    2. private Rigidbody2D body;
    3.     [SerializeField]
    4.     private float maxMoveForce;
    5.     [SerializeField]
    6.     private float movementForce;
    7.     [SerializeField]
    8.     private float jumpForce;
    9.  
    10.     void Start()
    11.     {
    12.         body = GetComponent<Rigidbody2D>();
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         if (Input.GetKey(KeyCode.D))
    18.         {
    19.             if (Mathf.Abs(body.velocity.x) < maxMoveForce)
    20.             {
    21.                 body.AddForce(Vector2.right * Time.deltaTime * movementForce * 100);
    22.             }
    23.         }
    24.         if (Input.GetKey(KeyCode.A))
    25.         {
    26.             if (Mathf.Abs(body.velocity.x) < maxMoveForce)
    27.             {
    28.                 body.AddForce(Vector2.left * Time.deltaTime * movementForce * 100);
    29.             }
    30.         }
    31.         if (Input.GetKeyDown(KeyCode.Space))
    32.         {
    33.             body.AddForce(Vector2.up * jumpForce);
    34.         }
    35.     }

    So if you want it to rotate around according to your mouse it would be -

    Code (CSharp):
    1.  
    2.     private float rotationOffSet = -90f;
    3.  
    4.  
    5.     void Update () {
    6.         if (Time.timeScale != 0)
    7.         {
    8.             RotateToMousePosition();
    9.         }
    10.     }
    11.  
    12.     void RotateToMousePosition()
    13.     {
    14.         Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10f);
    15.         float angle = AngleBetweenPoints(transform.position, mouseWorldPosition);
    16.  
    17.         transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle - rotationOffSet));
    18.     }
    19.  
    20.     float AngleBetweenPoints(Vector2 a, Vector2 b)
    21.     {
    22.         return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
    23.     }