Unity C#中的碰撞和方向?

时间:2017-03-14 03:05:18

标签: c# unity3d collision-detection

我正在使用此代码向正确的方向移动:

transform.Translate(1,0,0);

然后我用它来向相反方向移动,我需要改变x轴正/负。

void OnCollisionEnter2D(Collision2D col){

}

帮助我实现目标...... 提前谢谢。

3 个答案:

答案 0 :(得分:0)

这对我这样的新手来说,对我有用!

using UnityEngine;
using System.Collections;

public class CollisionAndtheMovement : MonoBehaviour {
    public float speed;
    public bool  toRight;`enter code here`
    // Use this for initialization
    void Start () {
        toRight = true;


    }

    // Update is called once per frame
    void Update (){
        if (toRight) {
            transform.Translate (Vector2.right*Time.deltaTime*speed, 0);
        }

        if (!toRight) {
            transform.Translate (Vector2.left*Time.deltaTime*speed, 0);
        }

    }

    void OnCollisionEnter2D(Collision2D col){
        if (col.gameObject.tag == "Crate" && toRight) {
            toRight = false;
        } else {
            toRight = true;
        }
    }
}

答案 1 :(得分:0)

您可以将transform.Right用于此目的和相反的方向 -transform.Right会做到这一点。

答案 2 :(得分:0)

为了反方向,只需将数字设为负数。

void OnCollisionEnter2D(Collision2D col){
  transform.Translate(-1,0,0);
}