Bruno Pigatto
Bruno Pigatto

Reputation: 67

Unity3d - Drag and Drop object 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?

Upvotes: 2

Views: 415

Answers (1)

Semimono
Semimono

Reputation: 724

The most obvious thing that should change is the z-value of curScreenPoint. Using the docs as reference, it should probably be:

Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);

Now for maybe a bit more fine-tuned behavior, you might want to make the object raise up above the ground if the ground has slopes or something with complex colliders on it like a chair or table. To do this, you likely want to do a sphere cast down towards the ground from a point somewhat above what's calculated in curPosition. Use the hitInfo to see how far down it goes, and adjust the y position of curPosition accordingly.

Upvotes: 1

Related Questions