创建scipt以允许拖动和捕捉

时间:2017-04-12 21:36:58

标签: c# unity3d

我有一个脚本,通过创建一个矢量数组,在表面上布置预制件。每个阵列包含14个矢量,这些矢量在平面上产生均匀间隔的位置。

public List<Vector3> handEastVectorPoints = new List<Vector3>();
public List<Vector3> handSouthVectorPoints = new List<Vector3>();
public List<Vector3> handNorthVectorPoints = new List<Vector3>();
public List<Vector3> handWestVectorPoints = new List<Vector3>();

然后当实例化预制件时,我的代码从正确的数组中获取正确的向量,并添加预制件,如下所示:

public IEnumerator addTileInHand(GameObject tile, Vector3 v, float time, Vector3 rotationVector, int pos)
    {

        Quaternion rotation = Quaternion.Euler(rotationVector);
        GameObject newTile = Instantiate(tile, v, rotation);
        tile.GetComponent<TileController>().canDraw = true;
        tile.GetComponent<TileController>().gameStatus = getCurrentGameState();
        tile.GetComponent<TileController>().currentTurn = sfs.MySelf.Id;

        PlayersHand[pos] = newTile;
        yield return new WaitForSeconds(time);
    }

调用此函数时,它会传递一个来自上面数组的向量。创建预制件,并将其添加到游戏对象数组中。

我现在要做的是让玩家拖放到各个&#34;热点&#34;,如第一组数组中所定义的(再次,它们是14个向量)并放下它们。如果在该位置已经预制了一个预制件,我希望它能够弹出刚刚打开的新位置。如果瓷砖在其他任何地方被丢弃,它应该快速回到其原始位置。我还想让对象向左或向右拖动,无需向上或向下拖动Y轴。

有人能指出类似可能有帮助或提供帮助的脚本吗?

感谢

编辑:可拖动脚本让这个工作。你只能在X轴上拖动,但对于我的用例,这可行。

public class DraggableObject : MonoBehaviour {
    private bool dragging = false;
    private Vector3 screenPoint;
    private Vector3 offset;
    private float originalY;

    void Start()
    {
        originalY = this.gameObject.transform.position.y;
    }
    void OnMouseDown()
    {
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, originalY, screenPoint.z));


    }

    void OnMouseDrag()
    {
        Vector3 cursorPoint = new Vector3(Input.mousePosition.x, originalY, screenPoint.z);
        Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
        transform.position = cursorPosition;
        dragging = true;
    }

    void OnMouseUp()
    {
        dragging = false;
    }

}

1 个答案:

答案 0 :(得分:0)

我为我的游戏做了类似的事情。这很容易。如果您有任何疑问,请按照以下步骤告诉我们:

  • 编写一个脚本(让我们说 HolderScript )并添加一个布尔 占用 对它。在脚本中添加OnTriggerEnter (A Monobehaviour function)并相应地更新布尔值:

    案例1 - 未占用持有人 - 将布尔值设为true并禁用碰撞器(如果预制件放在那里),否则什么都不做。

    案例2 - 持有人被占用 - 如果已删除占用的预制件,则在OnTriggerExit function中将布尔值设为false并启用碰撞器。

  • 编写一个脚本(让我们说DraggableObject)并相应地设置拖动和isDropped布尔值,你可以使用Lerp function进行回弹。

将holder脚本附加到droppable区域,将DraggableObject脚本附加到可拖动对象。 这应该可以解决您的问题。