- Home /
How to make a 2d mouse look script
Hello. I've been working on a 2d game, but I've run into a problem with a standard function. 1. How do you make a object rotate to face the cursor? and 2. How do you make the crosshair follow the mouse.
Thanks.
Answer by Not showing my name · Sep 01, 2010 at 12:30 PM
Considering you have a GUI Crosshair texture, here's the code you use.
var crosshairTexture : Texture2D;
var position : Rect;
function Start() { position = Rect( ( Screen.width - crosshairTexture.width ) / 2, ( Screen.height - crosshairTexture.height ) / 2, crosshairTexture.width, crosshairTexture.height ); }
function OnGUI() { GUI.DrawTexture(position, crosshairTexture);
}
...and that's how. about that 2d rotator thing... I absolutely have no idea. PS make sure to have the GUI Crosshair set into the script. remember, the script is in the camera!
Answer by BoydHamilton · Jun 08, 2020 at 09:08 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
void Update()
{
MouseLook2D();
}
void MouseLook2D()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y
);
transform.up = direction;
}
}
Your answer
