Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class LookAtMouse : MonoBehaviour
- {
- Camera MainCam;
- private void Start()
- {
- //Unity allows us to assign the main camera by a MainCamera tag
- MainCam = Camera.main; //same as FindGameObjectsWithTag
- }
- void Update()
- {
- /*1.) First thing you need to know is that the mouse and the character is not on the same grid.
- * The mouse is in screen space, the character in world space */
- //Instead of using an ray to bring the mouse into the world, we can just check the characters screen space
- Vector3 ViewportPos = MainCam.WorldToScreenPoint(this.transform.position);
- /*2.) Now we need to use offset, you learn this in school alonsgide Pythagoras theorem,
- * because that is how you get the length of the vector and direction */
- Vector3 offset = Input.mousePosition - ViewportPos; // Offset is the difrince in vector space
- //The Unity normalized function uses the theorem to find the distance and then devides the vector with it
- Vector3 EulerDirection = offset.normalized;
- //There is just one little problem, this works for 2D space not 3D, we need the Y as the Z
- EulerDirection = new Vector3(EulerDirection.x, 0, EulerDirection.y);//fixed it just like that
- //3.) Now that we have the direction we just set the rotation to look in that direction
- this.transform.rotation = Quaternion.LookRotation(EulerDirection);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement