- Home /
Drag and Drop on RTS camera
I have this code to drag and drop 3d objects on a world:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpyAI : MonoBehaviour {
Animator anim;
private Vector3 screenPoint;
private Vector3 offset;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
void OnMouseDown()
{
anim.SetBool("drag", true);
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
void OnMouseUp()
{
anim.SetBool("drag", false);
anim.SetBool("idle", true);
}
}
The problem is: When im dragging the object, sometimes, depending on the mouse movement it goes undergound How can I make the object to stay above the ground while dragging it?
You're going to have to raycast against the ground to test its elevation and also get the object's y axis extents and add both to your offset. You can also get the ground normal and adjust the rotation of your object to the ground normal if you like.
Answer by YBtheS · Jul 02, 2018 at 09:57 PM
Use a raycast whose origin is at the dragged objects position that goes downwards. Should look like this:
RaycastHit hit;
Ray ray = new Ray(new Vector3(selectedObjectPos), Vector3.down);
Debug.Log(hit.point.y);
This should print the y coordinate of the collider under the dragged object (selectedObjectPos is the position of the dragged object). You may need to account for the objects size so I believe that you would need to subtract the Collider.bounds.extents.y of the dragged object from the hit.point.y like so: yPos = hit.point.y - selectedObject.GetComponent<Collider>().bounds.extents.y;
Note that this is in C#.
Hope that helps!
Thank you. It worked. Here's the code:
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
Ray ray = new Ray(new Vector3(transform.position.x, transform.position.y, transform.position.z), Vector3.down);
float yPos = hit.point.y - collidedrr.bounds.extents.y;
transform.position = new Vector3(curPosition.x, -yPos, curPosition.z);