按箭头时尝试移动立方体并交换2个立方体

时间:2014-04-21 07:01:12

标签: c# unity3d

我想在Unity的2D模式下左右移动带有箭头键的立方体。

我想将多维数据集的位置与附加的碰撞器交换,但代码似乎根本不起作用。

public float Jump = 0.6f;
Vector3 positionP, positionS, position, pos;
public GameObject Swapable;
public GameObject Player;

void Start ()
{
        positionS = Swapable.transform.position;
        positionP = Player.transform.position;
}

// Update is called once per frame
void Update ()
{

        if (Input.GetKey (KeyCode.RightArrow)) {
                transform.position = Vector2.right * Jump;
        }
        if (Input.GetKey (KeyCode.LeftArrow)) {
                transform.position = -Vector2.right * Jump;
        }
}

void OnTriggerEnter2D (Collider2D col)
{
        if (col.Equals ("Red")) {
                Debug.Log ("Touched");
                position = positionS;
                pos = positionP;
                Player.transform.position = position;
                Swapable.transform.position = pos;

        }
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你的立方体只移动到(0.6,0),而不是翻译。

在您的更新方法中,您致电:

transform.position = Vector2.right * Jump;

Vector2.right总是返回(1,0)。跳跃总是0.6

所以你总是将你的位置设置为(0.6,0)而你需要递增它。

transform.position = transform.position + Vector2.right * Jump

尝试此更改,看看您的立方体是否至少现在移动。从那里我们可以尝试修复任何碰撞错误。

修改

好的,这将为您处理交换。您将需要一个主游戏对象,该脚本管理整个网格。如果要交换头寸,请调用交换功能。

public class TilePositions
{
    //The objects in your grid
    public Transform[,] objects;

    //Offset from (0,0) that your grid's top-left is at.
    public Vector3 offset;

    //Scale of your grid
    public Vector2 scale;

    //Swap the objects at position one and position two in the grid
    public void Swap(Point one, Point two)
    {
        var temp = objects[one.x,one.y];

        objects[one.x,one.y] = objects[two.x,two.y];
        objects[two.x,two.y] = temp;

        objects[one.x,one.y].Position = new Vector3(one.x,one.y,0) * scale + offset;
        objects[two.x,two.y].Position = new Vector3(two.x,two.y,0) * scale + offset;
    }

    /// <summary>
    /// Converts a transform's vector3 position to a Point struct
    /// </summary>
    /// <param name="obj">The transform whose position is to be converted</param>
    /// <returns>System.Drawing.Point for the grid's position</returns>
    private Point PositionToPoint(Transform obj)
    {
        var position = (obj.Position - offset) / scale;
        return new Point((int)position.x, (int)position.y);
    }
}