- Home /
Convert Mouse Position - To Transform
Hello,
I want a sphere to follow my mouse, but I don't want the sphere to use dept (Z axis). I basically want the ball to stick to my mouse position absolutely (like a custom curser texture)... But within my 3D scene.
What I'm trying to do, is that when you click on an object (a car) in the scene, a sphere pops up in the same 3D position as the car in the scene. You can then drag this sphere only X, Y on the screen so it appears its stuck to the mouse. Another note is that my camera can move around the scene (don't know if that will effect the maths of my sphere)
This is what I have at the moment:
function Drag() {
selectedPullingPoint = currentSelected.GetComponent(JengaBlock).pullPoint;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, Mathf.Infinity)){
if(!pullingApart){
start.position = selectedPullingPoint.position;
pullingApart = true;
}
//not used atm
var screenX = Input.mousePosition.x;
var screenY = Screen.height - Input.mousePosition.y;
//Rotate end object towards camera
//end.rotation = Quaternion.LookRotation(-Camera.main.transform.forward);
//Moves end object
end.position = hit.point; //Vector3(screenX, screenY, start.position.z);
end.position.z = start.position.z;
}
Thanks
Answer by kat0r · Sep 26, 2013 at 03:44 PM
You create a new Plane, with origin at the object's position, and a normal pointing to your camera. Then you intersect that plane with your mouse-cursor-ray, and move that object to the intersection. As you recreate the plane every frame, movement of the camera doesn't matter.
Edit: maybe it would look better if you used the direction of the camera as a normal.
I have no idea how to do any of that. Why a plane? Whats a normal?
Normals are a VERY basic math/geometry/3d graphics concept, so please google them. For your purpose, what you want is that the object moves in "2D" without Z. A plane is handy, because the camera already uses planes - the near and far plane (https://en.wikipedia.org/wiki/Viewing_frustum). If you move an object on a plane that is parallel to those, the depth doesn't matter, it moves in 2D.
To define a plane in Unity3d, you just use code like "Plane p = new Plane(Vector3 inNormal, Vector3 inPoint);" inPoint is a point on the plane - your object, the inNormal gives the direction of the plane (google that). Now you can just do p.Raycast, and get the intersection.
Your answer
Follow this Question
Related Questions
Mouse position on 4.6 Canvas 0 Answers
How to make object fallow the mouse ?? 1 Answer
Mouse.position from center of player 1 Answer
Raise/Lower terrain height? - javascript. 1 Answer
Rotate a thrown spear to Mouse Position (2d top down game) 0 Answers