- Home /
Drag and Drop with perspective camera 3D
Hello!
I want to drag and drop 3d objectives in 3D Space with a perspective camera (55° top down). Is there a chance to get the objective always in the same hight in 3d space over a terrain?
Answer by Simeon · Jan 27, 2015 at 09:09 AM
Just use a Plane to raycast with a ray from the camera, if you are doing an RTS. or you can always shoot a ray from the camera Camera.ScreenPointToRay and get a point with a desired length r.GetPoint
Thank you! I know how it could work theoretical... Do you have any code examples?
I have a Terrain. On that terrain are some gameobjects with rigidbody on it. When I drag one of them with the mouse and move it arround, it should always have the same distance between it and the ground (uneven terrain). With those scripts out there (Unity Wiki e.g.), the y-position of the gameobject moves under the terrain for example. I want a fixed distance till drop...
When i use a camera with perfect 90° top down angle. It works. When i use 55° for my game, the objects move up on y position by moving mouse up and move down on y position by moving mouse down.
Example:
using System.Collections;
using UnityEngine;
class DragTransform : $$anonymous$$onoBehaviour
{
private bool dragging = false;
private float distance;
void On$$anonymous$$ouseDown()
{
distance = Vector3.Distance(transform.position, Camera.main.transform.position);
dragging = true;
}
void On$$anonymous$$ouseUp()
{
dragging = false;
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
}
ok, i solved the problem with the distance by asking for the distance in the Update function and not in the On$$anonymous$$ouseDown function:
void Update()
{
if (dragging)
{
distance = Vector3.Distance(new Vector3(transform.position.x, transform.position.y +1f,transform.position.z),Camera.main.transform.position);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(distance);
transform.position = rayPoint;
}
}
Now it works with the 55° angle... But there are some bugs on a navmesh baked on my terrain...
Your answer
Follow this Question
Related Questions
Drag 3d objects on a 3d scenario? 1 Answer
Drag n Drop in a 3D orthographic environment 1 Answer
UI drag and drop 1 Answer
kite game should be 2D or3d?? 0 Answers
Simple drag and drop - no physics 4 Answers