我正试图在画布上划一条蛇。我正在使用if else语句,目前线路从左到右,然后从右到左。但是在这里我被卡住了,它应该再次下降,然后再次从左到右。不确定我是否应该使用功能?
以下是pen
function setup(){
createCanvas(600,800);
background(250,180,20)
}
function draw(){
var left = 600;
var right = 800;
var speed = 3
timeline.move()
}
var timeline = {
speed : 3,
x : 20,
y : 20,
move : function(){
fill(0);
ellipse(this.x,this.y,20,20)
if(this.x<width-20){
this.x = this.x + this.speed
}
else if(this.y > 0){
this.y = this.y + this.speed}
if(this.y > 100 || this.x < 20){
this.y = this.y - this.speed
this.speed= this.speed*-1
this.x = this.x + this.speed+1}
if(this.x < 20 && this.y > 200){
this.y = this.y + this.speed
}
}
}
提前致谢
答案 0 :(得分:1)
我会尝试使用某种点或指令,而不是硬编码值。它可能会更容易构建。如果需要,您也可以将运动部分分解为更通用的功能。
以下是一些经过修改的代码:
function setup(){
createCanvas(600,800);
background(250,180,20)
}
var points = [
{x: 500, y:20},
{x: 500, y:80},
{x: 20, y: 80},
{x: 500, y: 300}
]
var currentPointIndex =0;
function draw(){
var left = 600;
var right = 800;
var speed = 3
timeline.move()
}
var timeline = {
speed : 5,
x : 20,
y : 20,
move : function(){
fill(0);
ellipse(this.x,this.y,20,20)
var didMove = false;
var currentPoint = points[currentPointIndex];
if(this.x < currentPoint.x - this.speed){
this.x += this.speed;
didMove = true;
}
else if(this.x > currentPoint.x + this.speed){
this.x -= this.speed;
didMove = true;
}
if(this.y < currentPoint.y - this.speed){
this.y += this.speed;
didMove = true;
}
else if(this.y > currentPoint.y + this.speed){
this.y -= this.speed;
didMove = true;
}
if(!didMove && currentPointIndex < points.length){
currentPointIndex++;
}
}
}
它快速而肮脏,但显示了一般的想法。希望它有用!