Get vector3 from cursor position relative to object in 3D plane
How is it possible to get a cursors X and Y Location relative to the scene planes rather than using co-ordinates based upon pixels of screen height and width?
I have the start of a very basic game, picture with a few physical aids shown below.
I want to find out how far away the cursor is on the X and Y axis from an object in the scene. The Z axis is irrelevant due to the nature and orientation of the game, so z = 0
Basically, the distance of the cursor from the cube on the X Axis upon clicking will define the power
of an action.
Because of this. I want to get the cursor X position relative to the 0 point of the scene ( or the object ), not relative to the bottom left corner of the screen.
I could then use Vector3.Magnitude()
to get the distance.
How is this possible?
Answer by Panomosh · Feb 25, 2016 at 12:33 PM
( Answer from Gamedev.Stackexchange by user: Wondra )
It is possible and Unity documentation is very helpful in this matter. First you need a ray to raycast from mouse position, the documentation for mouse > position provides an example how to get a ray from mouse position:
public class ExampleClass : MonoBehaviour {
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
}
because you are not interested in all of the objects(just the plane*), following to documentation of Physics.Raycast will tell you all possible overloads, one of them having a layer > mask. You are also interested in position, so choosing an overlaod with
RaycastHit
and following documentation to RaycastHit tells you there is a ".position":
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
int maskOfPlane = 1 << planeLayer;
if (Physics.Raycast(ray, out hit, maskOfPlane)) {
//one of coordiantes being always zero for aligned plane
var position = hit.position;//this is relative to 0,0,0
var relativePosition = other.transform.position - position;
//relative to a gameObject other
}
}
}
*literally place an invisible plane in the world aligned with your games logical plane and move it to a custom layer, you will need to set the mask against it.
Your answer
Follow this Question
Related Questions
Don't trust "Vector3.Distance"? 1 Answer
How to play animation depending on distance ?? (Video) 0 Answers
Distance is always zero 0 Answers
How I can make my camera keep a distance between two objects? 0 Answers
Dot Product not equals 1 0 Answers