2016-11-09 26 views
1

您好所有誰正在閱讀這篇文章 在試圖讓馬里奧類型的遊戲,但我有一些碰撞錯誤 也許有人能向我解釋什麼是不正確的,如何解決它JavaScript的碰撞檢測錯誤

碰撞部分那裏雖然是硬編碼值 我不能正確跳上框很難解釋,如果它不是硬只緩存js小提琴鏈接!

上箭頭的空間控制跳躍問題是跳躍 遊戲邏輯

Game logic Img

var hero = { 
 
    X: 200, 
 
    Y: 450, 
 
    gravity: 0.05, 
 
    gravitySpeed: 0, 
 
    speed: 2, 
 
    height: 50, 
 
    width: 50 
 

 
} 
 

 

 
var box = { 
 
    X: 300, 
 
    Y: 450, 
 
    height: 50, 
 
    width: 50 
 
} 
 
var map = { 
 
    gravity: 0.5, 
 
    groundY: 350 
 

 
} 
 
var optiones = { 
 
    crashWith: function (otherobj) { 
 
     var myleft = hero.X; 
 
     var myright = hero.X + (50); 
 
     var mytop = hero.Y; 
 
     var mybottom = hero.Y + (50); 
 

 
     var otherleft = box.X; 
 
     var otherright = box.X + (50); 
 
     var othertop = otherobj.y; 
 
     var otherbottom = box.Y + (50); 
 
     var crash = true; 
 
//Hard coded values 
 
     var Y = 450, 
 
      X = 300, 
 
      w = 50, 
 
      h = 50 
 
     // not tuching 
 
     if ((mybottom < othertop) || 
 
      (mytop > otherbottom) || 
 
      (myright < otherleft) || 
 
      (myleft > otherright)) { 
 
      crash = false; 
 
      //   console.log("dont tuch") 
 
      hero.Y += hero.gravitySpeed; 
 
      hero.gravitySpeed += hero.gravity; 
 
     } else { 
 
      // collision rules 
 
      if (mytop >= othertop && othertop < otherbottom) { 
 
       if (hero.X <= X) { 
 
        hero.X = X - hero.width 
 
       } else if (hero.X > X) { 
 
        hero.X = X + hero.width 
 
       } 
 
      } else if (hero.X >= X && hero.X <= X + w) { 
 

 
       if (hero.Y <= Y) { 
 

 
        hero.Y = Y - hero.height 
 
       } else if (hero.Y >= Y) { 
 
        hero.Y = Y + hero.height 
 
       } 
 
      } 
 

 

 
     }

這裏雖然是一個完整的代碼看或播放白衣它JS小提琴 js fiddle

+1

您的代碼段似乎有效,問題究竟是什麼? – DBS

+1

我可以去thro元素當我跳 –

+0

替換框與otherobj –

回答

1

您的功能說:

function crashwith(otherobj){} 

但是這裏面你說

othertop=box.y; 

特殊照顧不檢查是否與傳遞的對象英雄崩潰,但有一個盒子。那不是我認爲該功能應該做的。我想你想:

othertop=otherobj.y; 

而且您的碰撞防護功能必須

 if ((mybottom < othertop) || 
     (mytop > otherbottom) || 
     (myright < otherleft) || 
     (myleft > otherright)) { 
     Alert("crash"); 
     } 

你的邏輯是圓

+0

好吧它不適合我 –

+0

那不是好。但theres仍然是一個錯誤,請參閱我的編輯 –

+0

好吧我一邊玩,但我仍然卡住我剛更新了帖子!感謝您的重播 –

0

現在,我想這樣的事情

 if(myright >= otherleft && mybottom > othertop &&myleft < otherright){ 
     console.log("R______") 
     hero.X = otherleft - hero.width 
    } 
    if(myleft <= otherright && mybottom > othertop && myright > otherleft){ 
     console.log("L______") 
     hero.X = otherleft + hero.width 
    } 
+0

您的邏輯依然是錯誤的... –

+0

好吧現在我真的不明白如何改變我的邏輯你能幫助..? –

0
其他方式

我如何理解我不需要這部分

 if ((mybottom < othertop) || 
     (mytop > otherbottom) || 
     (myright < otherleft) || 
     (myleft > otherright)) { 
     crash = false; 
+0

您的代碼適用於正常的數學圖形,但畫布的y軸向下。所以y越高,盒子越低(可能我在我的大腦中產生了一些混亂,但我認爲它是這樣) –

+0

哦,對不起你的邏輯是對的,我錯了:( –

+0

請檢查遊戲邏輯img我絕對不會把它添加到帖子 –