Object is stuck at center of camera instead of following mouse
I have been trying to make my game object follow the cursor but it's moving with the center of the camera instead. In my game, the camera follows the player as they move. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CrosshairBehaviour : MonoBehaviour
{
private void Update()
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(mousePos.x, mousePos.y, 0f);
}
}
Answer by I_Am_Err00r · Aug 12, 2019 at 06:08 PM
Hey there, I like your handle by the way @StrangeDew !
Is this script attached to just your crosshair? Is your player gameObject a parent of this crosshair? Maybe you just need to add a GameObject variable to your code to define what the cross hair is.
So I never use the mouse position personally, but I just tested this code and it worked exactly as you would probably want your code to (you need to add your crosshair prefab in the inspector for it to work):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Crosshair: MonoBehaviour
{
public GameObject crossHair;
void FixedUpdate()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
crossHair.transform.position = mousePos;
}
}
I noticed you have the z axis set to 0, just use a Vector2 for mousePos and you don't need to worry about that z axis; I couldn't tell you exactly why your code wasn't working, but I got mine to work so that your mouse position moves the cross-hair.
Someone else with more coding knowledge might be able to definitively tell you when to use Update vs FixedUpdate, but I tend to make anything that handles movement of objects in FixedUpdate, and generally save Update for input handling and things like that (it has to do with framerates and from what I understand FixedUpdate is a better universal solution for movement handling because of the stability in the frames it's checking, where Update checks based on framerate and can cause stuttering at fluctuating rates, here is an answer on it), just best practice.
I figured it out. I needed to set the z-axis to -10f. Apparently, ScreenToWorldPoint() takes into account the distance of the plane from the camera in the world.
I believe if you use a Vector2 like I had in the example it would fix that issue, but I could be wrong.
If you could humor me and try that, I'm curious (I'm at work and don't have access to Unity, but if you don't respond I will just test out when I'm home; I just want to make a mental note).
Answer by AMMARx · May 24 at 08:58 PM
I know I'm late but I have been threw this problem until I figured out how to resolve it:
Just change the camera projection to Orthographic