Advertisement
MysteryGM

Unity_3DTopDown_LookAtMouse

Jul 11th, 2020
1,348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class LookAtMouse : MonoBehaviour
  6. {
  7.     Camera MainCam;
  8.  
  9.     private void Start()
  10.     {
  11.         //Unity allows us to assign the main camera by a MainCamera tag
  12.         MainCam = Camera.main; //same as FindGameObjectsWithTag
  13.     }
  14.  
  15.  
  16.     void Update()
  17.     {
  18.         /*1.) First thing you need to know is that the mouse and the character is not on the same grid.
  19.          * The mouse is in screen space, the character in world space */
  20.  
  21.         //Instead of using an ray to bring the mouse into the world, we can just check the characters screen space
  22.         Vector3 ViewportPos = MainCam.WorldToScreenPoint(this.transform.position);
  23.  
  24.         /*2.) Now we need to use offset, you learn this in school alonsgide Pythagoras theorem,
  25.          * because that is how you get the length of the vector and direction */
  26.         Vector3 offset = Input.mousePosition - ViewportPos; // Offset is the difrince in vector space
  27.         //The Unity normalized function uses the theorem to find the distance and then devides the vector with it
  28.         Vector3 EulerDirection = offset.normalized;
  29.  
  30.         //There is just one little problem, this works for 2D space not 3D, we need the Y as the Z
  31.         EulerDirection = new Vector3(EulerDirection.x, 0, EulerDirection.y);//fixed it just like that
  32.  
  33.         //3.) Now that we have the direction we just set the rotation to look in that direction
  34.         this.transform.rotation = Quaternion.LookRotation(EulerDirection);
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement