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

main charicter won't follow mouse

Discussion in 'Scripting' started by stevenbos655, May 3, 2020.

  1. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerMovement : MonoBehaviour
    4. {
    5.     public float moveSpeed = 5f;
    6.     public Rigidbody2D rb2d;
    7.     public Camera cam;
    8.     Vector2 movement;
    9.     Vector2 mousePos;
    10.     void Update()
    11.     {
    12.         movement.x = Input.GetAxisRaw("Horizontal");
    13.         movement.y = Input.GetAxisRaw("Vertical");
    14.     }
    15.     void FixedUpdate()
    16.     {
    17.         rb2d.MovePosition(rb2d.position + movement * moveSpeed * Time.fixedDeltaTime);
    18.         Vector2 lookDir = mousePos - rb2d.position;
    19.         float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
    20.         rb2d.rotation = angle;
    21.     }
    22. }
    23.  
     
    Last edited: May 3, 2020
  2. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    Assets\PlayerMovement.cs(11,13): warning CS0649: Field 'PlayerMovement.mousePos' is never assigned to, and will always have its default value
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    The error is pretty clear. I think you forgot something like this in your Update() method:
    Code (CSharp):
    1. mousePos = Input.mousePosition;
     
  4. stevenbos655

    stevenbos655

    Joined:
    May 1, 2020
    Posts:
    14
    thank you but I already fixed the issue but I was wondering how you delete a thread