- Home /
My crosshair is moving the opposite of the mouse position. Why?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class pointShoot : MonoBehaviour { int neg = -1; public GameObject crosshairs; private Vector3 target;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
}
}
I have this 3d platformer game. I created this code but my crosshair is moving the opposite of the mouse position. i tried to multiply the values by -1 but then the crosshair just wasn't on the screen. Help :(
Answer by Hellium · Apr 14, 2021 at 08:26 PM
The z
component of the Vector3 you pass to ScreenToWorldPoint
is the distance from the camera the resulting vector should be.
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class pointShoot : MonoBehaviour
{
public Transform Crosshair;
private Camera camera;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
camera = GetComponent<Camera>();
}
void Update()
{
Vector3 screenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Mathf.Abs(Crosshair.position.z - transform.position.z));
Crosshair.position = camera.ScreenToWorldPoint(screenPoint);
}
}
Your answer
Follow this Question
Related Questions
Air Strike shoot aiming at cross hairs in middle of the screen 2 Answers
2D Platform Shooter Camera Controls C# 0 Answers
Random Raycast inside crosshairs 1 Answer
laser pointer 1 Answer
Shooting Accuracy Problem 0 Answers