简体   繁体   English

Unity C#中的碰撞和方向…?

[英]Collision and direction in Unity C#…?

I'm using this code to move to right direction: 我正在使用此代码向正确的方向移动:

transform.Translate(1,0,0);

Then I'm using this to move to opposite direction, I need to change x axis positive/negative. 然后,我使用它向相反方向移动,我需要将x轴更改为正/负。

void OnCollisionEnter2D(Collision2D col){

}

Help me to make it happen.... Thanks in advance. 帮我实现它。...在此先感谢。

This Is for newbie like me, it's work for me! 这是给像我这样的新手使用的,对我来说有用!

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;
        }
    }
}

您可以将transform.Right用于此目的,也可以用于相反方向-transform.Right可以解决问题。

To go the opposite direction, just make the number negative. 要相反,只需将数字设为负数即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM