- Home /
How to make mouse cursor move automatically onto a 3D object in the scene
Hi,
I have a scene whose only 3D object is a sphere and I want when pressing a key (say, Shift Key), the mouse cursor to move automatically onto the sphere. For that purpose, I've written the following piece of code but it only works for specific camera angles and positions and only when Unity Editor's 'Game' window is set to 'Maximize On Play':
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System;
public class CursorMove: MonoBehaviour {
public struct Point {
public int X;
public int Y;
public Point (int _X, int _Y) {
X = _X;
Y = _Y;
}
}
[DllImport("user32.dll")]
private static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
private static extern bool GetCursorPos(out Point pos);
public Transform target;
private Point CurrentCursorPosition, NextCursorPosition;
void Update() {
if (Input.GetKeyUp(KeyCode.LeftShift)) {
CurrentCursorPosition = new Point ();
GetCursorPos (out CurrentCursorPosition);
Vector3 Coords = GetComponent<Camera> ().WorldToViewportPoint (target.position);
Point Coords_AdjustedToResolution =
new Point ((int)(Coords.x * (float)Screen.currentResolution.width),
(int)(Coords.y * (float)Screen.currentResolution.height));
NextCursorPosition =
new Point (Coords_AdjustedToResolution.X, Coords_AdjustedToResolution.Y);
SetCursorPos (NextCursorPosition.X, NextCursorPosition.Y);
}
}
}
What should I do to make it work for all camera angles and positions?
Thanks in advance.
Have you tried using https://docs.unity3d.com/ScriptReference/Camera.WorldToScreenPoint.html rather that to viewportpoint? cant test it but i think it might work since transform the point into the screen position so angles and positions should not be affected.
Yes, I have tried WorldToScreenPoint too, but to no avail. In fact, it gives less accurate results than WorldToViewportPoint. I guess some extra calculations regarding the screen resolution need to be included.
Have you considered writing your own ingame cursor? Depending on the rest of your game setup this might be the simplest solution. Basic steps would be: - Lock the actual mouse at center and hide it. - Display a custom ui widget with your custom cursor. - move the widget by getting the mouse input - or set its onscreen position by simply giving it the ui intersection of a camera to target raycast.
Answer by VaSiLiZz · Apr 22, 2019 at 09:07 PM
I solved it! The only thing I needed to do is to change the assignment at line 39 into the following:
Point ScreenCoords_AdjustedToResolution = new Point ((int)(ScreenCoords.x),
(Screen.currentResolution.height - (int)(ScreenCoords.y)));
The subtraction from Screen's height takes places because the Y-coordinate in a Scene increases upwards, unlike Screen's Y-coordinate which increases downwards.
I should also mention that this method works only in full screen mode.
Your answer
