简体   繁体   English

C# 移动限制蛇游戏

[英]C# movement limit snake game

I'm a new programmer and I wanted to create a snake game for fun and to learn.我是一名新程序员,我想创建一个贪吃蛇游戏来娱乐和学习。

This is my code for movement:这是我的运动代码:

private Vector2 _direction = Vector2.right;

private void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
    {
        _direction = Vector2.up;
    }
    else if (Input.GetKeyDown(KeyCode.S))
    {
        _direction = Vector2.down;
    }
    else if (Input.GetKeyDown(KeyCode.D))
    {
        _direction = Vector2.right;
    }
    else if (Input.GetKeyDown(KeyCode.A))
    {
        _direction = Vector2.left;
    }
}

I wanted to add a code that if the snake was moving up, it does not move down, or if it was moving left does not move right, and other directions.我想添加一个代码,如果蛇向上移动,它不会向下移动,或者如果它向左移动不会向右移动,以及其他方向。

And I wanted to know how to call arrows for movement.我想知道如何调用移动箭头。

So what do I do?那我该怎么办?

Thanks for helping <3 I just joined stack overflow:)感谢帮助 <3 我刚刚加入堆栈溢出:)

private Vector2 _direction = Vector2.right;

int currentdirection = 1;
//0-up , 1-right, 2-down, 3-left

private void Update()
{
    if (Input.GetKeyDown(KeyCode.W) && currentdirection != 2  )
    {
        _direction = Vector2.up;
        currentdirection = 0;
    }
    else if (Input.GetKeyDown(KeyCode.S))
    {
        _direction = Vector2.down;
        currentdirection = 2;
    }
    else if (Input.GetKeyDown(KeyCode.D))
    {
        _direction = Vector2.right;
        currentdirection = 1;
    }
    else if (Input.GetKeyDown(KeyCode.A))
    {
        _direction = Vector2.left;
        currentdirection = 3;
    }
}

This is the start of a simple solution.这是一个简单解决方案的开始。 It has an int that keeps track of the direction the snake is moving.它有一个 int 来跟踪蛇的移动方向。 The if statement at the top has been modified to only change direction if the W key is pressed AND the current direction is not down.顶部的 if 语句已被修改为仅在按下 W 键且当前方向不是向下时才更改方向。 You can add something similar to the other three if statements.您可以添加类似于其他三个 if 语句的内容。

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

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