抓住并放下物体

时间:2016-01-12 14:58:57

标签: c# unity3d

我正在尝试新事物而且我一直想找到一种拖放物体的方法。我的球员是一个正方形,他有一只手。这是一个例子:

Example

手臂上的红色东西是"手",当我按下shift时它会变成绿色。我做了检测,就像一次地面检查。这是代码:

void Update () {
        touch = Physics2D.OverlapCircle(touchDetect.position, 0.01f, objectLayer);
        mao1.SetBool("Ligado", ligado);

        if (Input.GetKey(KeyCode.LeftShift)) {
            ligado = true;
        } else {
            ligado = false;
        }        
    }

touchDetect工作正常,因为他转向" true"当接触盒子时:

Example2

我的问题是:我不知道如何放入脚本,我希望他抓住对象并在我想要的时候丢弃。如果我需要使用Raycast,代码将如何?

2 个答案:

答案 0 :(得分:1)

为了“统一”一个对象,只需将你想要抓取的游戏对象的transform.parent设置为你希望抓住它的游戏对象的变换。

例如,在您的代码中,您使用Physics2D.OverlapCircle返回Collider2D个对象。您可以使用该对撞机抓住您的游戏对象。

Collider2D touch = Physics2D.OverlapCircle(touchDetect.position, 0.01f, objectLayer);

if (Input.GetKey(KeyCode.LeftShift) && touch != null) 
{
    //grab on to the object
    touch.gameObject.transform.parent = this.transform;

    //if your box has a rigidbody on it,and you want to take direct control of it
    //you will want to set the rigidbody iskinematic to true.
   GetComponent<Rigidbody2D>().isKinematic = true;
} 
else if( touch != null)
{
    //let the object go
    touch.gameObject.transform.parent = null;

    //if your object has a rigidbody be sure to turn kinematic back to false
    GetComponent<Rigidbody2D>().isKinematic = false;
} 

答案 1 :(得分:1)

只需将带有SprieRender组件的GameObject放置到手尖即可。

将此脚本放入该qube并按照我评论的内容

using UnityEngine;
using System.Collections;

public class collid : MonoBehaviour {

// Use this for initialization

public Sprite mySprite; // Put Here that Qube Sprite
public GameObject Cursorimg; // Put the gameobject here from hierarchy

void Start () {
    mySprite = GetComponent<SpriteRenderer>().sprite;
}
// Update is called once per frame
void Update () {

    if(Collide conditions) {
     Debug.Log(" Collide ");
     Cursorimg.GetComponent<SpriteRenderer>().sprite = mySprite;
     Cursorimg.GetComponent<SpriteRenderer>().sortingOrder = 3;// U change based on your option
    }
    if(DropCondition)
    {
     Debug.Log("Drop");
     Cursorimg.GetComponent<SpriteRenderer>().sprite =null;
    }
}

如果这不起作用这是一个脚本,带有Sprite的游戏对象将跟随鼠标位置,

    Vector3 pos = Input.mousePosition;
    pos.z = Cursorimg.transform.position.z - Camera.main.transform.position.z;
    Cursorimg.transform.position = Camera.main.ScreenToWorldPoint(pos);

此代码在更新后面,Cursorimg是Gameobject

我认为这会对你有所帮助,让我进一步了解