Search Unity

Question Top-Down: Mouse Position wrong when player moves/turns...

Discussion in 'Scripting' started by rYkers, Apr 20, 2021.

  1. rYkers

    rYkers

    Joined:
    Mar 31, 2016
    Posts:
    4
    Hello,
    iam trying to draw a line from players postion to mouse position,
    that works well as long as the player is at 0,0,0.
    When rotating the player or moving him around to 0,180,0 the mouse axis are mirrored.
    I dont know how to update the rotation, can somebody please help me.

    (Script is attached to a child go of the player, player has a click to move script on it, Camera is perspective and follows the player.)
    Code (CSharp):
    1.  
    2. private Vector3 GetMousePos(){
    3.  
    4.         Ray cameraRay = camera.ScreenPointToRay(Input.mousePosition);
    5.         Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
    6.         float rayLength;
    7.  
    8.         if(groundPlane.Raycast(cameraRay, out rayLength)){
    9.  
    10.             Vector3 endPos = cameraRay.GetPoint(rayLength);
    11.  
    12.             endPos.y = 0;
    13.             Debug.DrawLine(transform.position, endPos, Color.blue);
    14.             return endPos;
    15.         }
    16.  
    17.         return Vector3.zero;
    18. }
    Code (CSharp):
    1.  
    2. private void DrawFromCenter(){
    3.  
    4.         var mousePos = GetMousePos();
    5.  
    6.         var difference = mousePos - transform.position;
    7.         var direction = difference.normalized; // normalize to only get a direction with magnitude = 1
    8.         var endPosition = startPosition + direction;
    9.  
    10.         line.SetPosition(0, startPosition);
    11.         line.SetPosition(1, endPosition);
    12. }
     
    Last edited: Apr 20, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,749
    Unfortunately the above is far too vague for anyone here to supply useful suggestions.

    I recommend looking for Youtube tutorials teaching you how to do <insert whatever the most-popular game you are trying to clone here> in Unity. The mouse stuff is going to be the most-trivial part of all of it so don't get hung up on it, just see how other people have solved it and move forward to the hard parts of making a game.
     
  3. rYkers

    rYkers

    Joined:
    Mar 31, 2016
    Posts:
    4
    Thanks for your reeply kurt.
    I solved it by setting the linerenderer in the inspector, where the rotation will be updated correctly.
     
    Kurt-Dekker likes this.