在unity3d中拖动一个对象

时间:2014-07-21 08:28:31

标签: c# unity3d drag

我想将一个物体拖到一个特定的地方。如果我在到达那个特定区域之前释放拖动的物体,物体应该到达我开始拖动的初始位置。怎么可能?对此有什么具体动议吗?

void OnMouseDown()
 {

 drag = true;
//Debug.Log("haii ");
}
void OnMouseDrag()
{
if(drag)
{
    var pos =Input.mousePosition;
    pos.x =Mathf.Clamp(pos.x,0,Screen.width);
    pos.y =Mathf.Clamp(pos.y,0,Screen.height);
    if(zdist>0)
    {
    zdist=Vector3.Distance(Camera.main.transform.position,transform.position);
        pos.z=zdist;
        pos = Camera.main.ScreenToWorldPoint(pos);
        transform.position =pos;

    }
}
}

1 个答案:

答案 0 :(得分:0)

您可以在案件中使用OnMouseUp() 我们的想法是检查对象是否在特定区域内 WHEN 用户释放他的点击。

您可以使用OnTriggerEnter()检查对象是否已到达该区域 如果您的物体仍然在该区域之外,则返回其原始位置。

对象的脚本:

void OnMouseDown(){
    // save the original position for later use
    originalPosition = gameObject.transform.position;
    ....
}

void OnMouseUp(){
    if(drag){
        if(!areaReached)
            gameObject.transform.position = originalPosition;
        // i don't see you set drag to false in your code,
        // when user has released his click, he cannot drag anymore
        // set it to false
        drag = false;
    }
}

该地区的剧本:

void OnTriggerEnter(Collider collider){
    // detect if the object enters the area
    if(collider.GameObject.name == "Your Object"){
        // get object's script and modify its variable
        ObjectScript obj = collider.GameObject.GetComponent<ObjectScript>();
        obj.areaReached = true;
    }
}

void OnTriggerExit(Collider collider){
    // set it back to false if the object leaves the area before OnMouseUp
    if(collider.GameObject.name == "Your Object"){
        ObjectScript obj = collider.GameObject.GetComponent<ObjectScript>();
        obj.areaReached = false;
    }
}