Unity2D Vector2不起作用

时间:2017-09-01 15:27:33

标签: c# position unity2d

所以我在Unity 2D中制作了Crossy Road克隆,我在第34行得到了一个错误 我不确定我错过了什么,但我需要另一个观点。 具体而言,我在此声明中收到错误:

if (transform.position != new Vector2(curPosition.x, transform.position.y) + nextDir) 

并且一切都标记为红色。

public class PlayerController : MonoBehaviour
{
    public Vector2 nextDir;
    public float jumpForce = 100;
    public float speed = 5;
    public float speedRot = 100;
    public float rotationOffset;
    Rigidbody rb;
    public Vector2 curPosition;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        curPosition = transform.position;
    }

    void Update()
    {
        if (transform.position != new Vector2(curPosition.x, transform.position.y) + nextDir)
        {
            transform.position = Vector2.MoveTowards(transform.position, new Vector2(curPosition.x, transform.position.y) + nextDir, speed * Time.deltaTime);
        }
        else
        {
            nextDir = Vector2.zero;
            curPosition = transform.position;
            curPosition.x = Mathf.Round(curPosition.x);
            curPosition.y = Mathf.Round(curPosition.y);
            if (Input.GetAxisRaw("Horizontal") != 0)
            {
                nextDir.x = -Input.GetAxisRaw("Horizontal");
                Move();
            }
            else if (Input.GetAxisRaw("Vertical") != 0)
            {
                nextDir.y = Input.GetAxisRaw("Vertical");
                Move();
            }
        }
    }

    void Move()
    {
        rb.AddForce(0, jumpForce, 0);
    }
}

1 个答案:

答案 0 :(得分:0)

可以通过在RequireComponent之上添加PlayerController属性来解决第一个错误(关于缺少[RequireComponent(typeof(Rigidbody2D)] public class PlayerController : MonoBehaviour { // rest of your code 组件):

    void Update()
    {
        // here you're trying to compare Vector3 ( transform.position )
        // to Vector2, (3 axis with 2 axis)
        //if (transform.position != new Vector2(curPosition.x, transform.position.y) + nextDir)
        // change it to this 
        Vector2 cmp = new Vector2(curPosition.x, transform.position.y) + nextDir;
        if(cmp[0] != transform.position[0] || cmp[1] != transform.position[1])
        {
            transform.position = Vector2.MoveTowards(transform.position, new Vector2(curPosition.x, transform.position.y) + nextDir, speed * Time.deltaTime);
        }
        // rest of the update's body
    }

    // rest of your code ...
}

并且您正在尝试将具有3轴的对象与具有2轴的对象进行比较

{{1}}