我有一個使用ProcessingJS庫碰撞在2D遊戲Processingjs
// Game
var player = {
x: 50,
y: 100,
width: 30,
height: 30,
speed: 10.5,
score: 0
};
var food = {
x: 200,
y: 200,
width: 30,
height: 30,
speed: 10.5
};
var up = 38;
var down = 40;
var left = 37;
var right = 39;
draw = function() {
background(155, 154, 156);
fill(0, 255, 85);
rect(player.x,player.y,player.width,player.height);
fill(245, 3, 3);
rect(food.x,food.y,food.width,food.height);
text('Score: ' + player.score,50,50);
};
var collided = function(){
if (player.x < food.x + food.width &&
player.x + player.width > food.x &&
player.y < food.y + food.height &&
player.height + player.y > food.y) {
return true;
} else {
return false;
}
};
keyPressed = function(){
switch(keyCode){
case up:
player.y -= player.speed;
break;
case down:
player.y += player.speed;
break;
case right:
player.x += player.speed;
break;
case left:
player.x -= player.speed;
break;
default:
break;
}
if(collided()){
while(collided()){
if(/* condition */){
// Do What?
};
}
}
};
我命名爲某些原因對象「食物」,所以不要拿這一點這段JavaScript代碼。 我試圖讓玩家與「食物」物體發生碰撞時,它會像「食物」物體是一個固體物體一樣行動,並且無法通過它(就像你試圖穿過牆壁。)
我試着從玩家的X位置減去1,直到碰撞停止。我將玩家移動到與「食物」物體的側面碰撞,並且運作良好。但是當我在物體的頂部或底部碰撞時,它會將玩家移動到物體的邊緣。我不知道如何解決這個問題,所以幫助將不勝感激。