gpt4 book ai didi

javascript - 使用 canvas 和 p5.js 移动正方形

转载 作者:行者123 更新时间:2023-11-29 23:06:16 28 4
gpt4 key购买 nike

我正在尝试使用 p5.js 和 HTML5 的 Canvas 元素移动一个正方形。

我尝试过以多种方式重新安排代码,有时当代码位于某些地方时, Canvas 并没有首先创建。无论我尝试了多少次,我似乎都无法让它工作。

它使用变量“direction”的原因是因为我计划让它根据按下的箭头键移动。

我的代码是这样的:

var snakeX = 0;
var snakeY = 0;
var snakeX2 = 20;
var snakeY2 = 20;
var direction = "right";
var alive = true;
var length = 2;

function setup() {
createCanvas(window.innerWidth, window.innerHeight)
frameRate(10);
}

function draw() {

background(0);
stroke(255);
fill(255);
rect(snakeX, snakeY, snakeX2, snakeY2);
}

if (direction == "up") {
snakeY = snakeY + 10
snakeY2 = snakeY - length
}

function move() {
if (direction == "down") {

snakeY = snakeY - 10
snakeY2 = snakeY + length
}

if (direction == "right") {
snakeX = snakeX + 10
snakeX2 = snakeX - length
}

if (direction == "left") {

snakeX = snakeX - 10
snakeX2 = snakeX + length
}

loop()
}
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
</body>

当我打开页面时,我希望正方形开始自动向右移动,但它保持静止。任何帮助将不胜感激!

最佳答案

如果我正确理解您的问题,可以通过执行以下操作解决动画问题:

  • draw() 函数中添加对 move() 的调用
  • 可选择将 if(direction == 'up') { .. } block 添加到 move()

这是您更新的代码段,以实际显示:

var snakeX = 0;
var snakeY = 0;
var snakeX2 = 20;
var snakeY2 = 20;
var direction = "right";
var alive = true;
var length = 2

function setup() {
createCanvas(window.innerWidth, window.innerHeight)
frameRate(10);
}

function draw() {

background(0);
stroke(255);
fill(255);
rect(snakeX, snakeY, snakeX2, snakeY2);

/* Ensure move() is called for each draw() */
move()
}


function move() {

/* Move this inside the brackets of move() */
if (direction == "up") {
snakeY = snakeY + 10
snakeY2 = snakeY - length
}

if (direction == "down") {

snakeY = snakeY - 10
snakeY2 = snakeY + length
}

if (direction == "right") {
snakeX = snakeX + 10
snakeX2 = snakeX - length
}

if (direction == "left") {

snakeX = snakeX - 10
snakeX2 = snakeX + length
}
}
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
</body>

希望对您有所帮助:)

关于javascript - 使用 canvas 和 p5.js 移动正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697993/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com