简体   繁体   English

像蛇一样的游戏-按下按钮后自动向一个方向移动

[英]Snake Like Game - Automatic Movement in one direction after pressing a button

so I am having troubles with automatic movement The code I am using is 所以我在自动运动方面遇到麻烦我正在使用的代码是

if (myGameArea.key && myGameArea.key == 40) {
      snake.y ++;
    }

which is moving but only when the key is hold, is there a way to let the object move in one direction automatically after just pressing the button. 它仅在按住键时才移动,有一种方法可以让对象在按下按钮后自动向一个方向移动。 Sorry, if that's a stupid question, I really am not an experienced coder. 抱歉,如果这是一个愚蠢的问题,我真的不是一个有经验的编码员。

You should consider giving the snake object another attribute: velocity! 您应该考虑赋予蛇对象另一个属性:速度! Since you are dealing with two dimensions you can define vx and vy as the two components of the velocity, and when a key is pressed you can change the velocity to the appropriate value, for example: 由于要处理二维,因此可以将vx和vy定义为速度的两个分量,并且在按下键时可以将速度更改为适当的值,例如:

if (myGameArea.key && myGameArea.key==40) {
    snake.vx = 0;
    snake.vy = 1;
}

As well as this, inside the snake object you should define the position by updating the current position. 除此之外,您还应该在蛇对象内部通过更新当前位置来定义位置。 For this you just add the current velocity. 为此,您只需添加当前速度。

Hopefully this gets you on the path to a working snake game! 希望这能使您踏上可行的蛇游戏之路! If not, let me know and I can try to help out more. 如果没有,请告诉我,我可以尝试提供更多帮助。

I would use flags, and when you press a key set the flag to true for a while loop. 我会使用标志,并且当您按一个键时,将标志设置为true,并进行一次while循环。 When you press a key, go to a move function and have it move the direction of the flag until another key is pressed or you hit a wall. 当您按下一个键时,转到移动功能并使其移动标记的方向,直到按下另一个键或碰到墙为止。

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

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