Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Last active August 9, 2023 10:57
Show Gist options
  • Save rsaenzi/acfec66cbfdd43a09613f63e883fa52d to your computer and use it in GitHub Desktop.
Save rsaenzi/acfec66cbfdd43a09613f63e883fa52d to your computer and use it in GitHub Desktop.
Script to make a gameobject look at the mouse position in Unity
//
// PointAtMouse.cs
//
// Created by Rigoberto Sáenz Imbacuán (https://linkedin.com/in/rsaenzi/)
// Copyright © 2021. All rights reserved.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PointAtMouse : MonoBehaviour {
Vector3 pointingTarget;
void Update() {
pointingTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.back * Camera.main.transform.position.z);
transform.LookAt(pointingTarget, Vector3.back);
}
void OnDrawGizmos() {
Gizmos.DrawSphere(pointingTarget, 0.2f);
Gizmos.DrawLine(transform.position, pointingTarget);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment