Unity 2D自上而下的碰撞

时间:2017-04-21 21:05:45

标签: c# unity3d 2d

我的Unity项目是2D Tron类似游戏,其中角色以恒定速度移动并且向上,向下,向左和向右改变方向,同时在其路径中留下线。一切正常。但我希望能够与它们以及地图周围的墙壁发生碰撞。我想使用光线投射碰撞来实现这一目标。基本上,如果一个墙在它前面,我希望角色不能朝着它移动的方向移动。事情是,当发生这种情况时,我真的不知道如何阻止这个角色。

我想要的一个例子是:

enter image description here

这是播放器的代码。

void Start(){
    direction = Vector2.down;
}

void Update(){
    Move(up, down, left, right);
    Collision();
}

void Move(KeyCode up, KeyCode down, KeyCode left, KeyCode right){
    position = transform.position;
    direction = (Input.GetKeyDown(up) && direction != Vector2.down)?Vector2.up:direction;
    direction = (Input.GetKeyDown(down) && direction != Vector2.up)?Vector2.down:direction;
    direction = (Input.GetKeyDown(left) && direction != Vector2.right)?Vector2.left:direction;
    direction = (Input.GetKeyDown(right) && direction != Vector2.left)?Vector2.right:direction;
    speed = (Input.GetKey(KeyCode.LeftShift))?2: 4;
    velocity = direction / speed;
    position += velocity;
    transform.position = position;
    Trail trail = Instantiate(trail1, transform.position, Quaternion.identity) as Trail;
    trail.color = (speed == 2)?new Color32(247, 118, 34, 255):new Color32(254, 174, 52, 255);
}

void Collision(){
    float rayLength = 10;
    RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, rayLength, collisionMask);
    Debug.DrawRay(transform.position, direction * rayLength, Color.red);
    if(hit){

    }
}

到目前为止,这会将射线引入玩家朝向的方向。为了让所有内容都透视,让我们说玩家以恒定的速度向左移动,而我并没有按下键。如果墙壁在玩家面前,它将无法穿过墙壁。

0 个答案:

没有答案