PIXI 碰撞檢測-PIXI文檔翻譯(6)

你現在知道如何製作各種各樣的圖形對象,但你能用他們做什麼?一個有趣的事情是構建一個簡單的碰撞檢測系統。你可以使用一個自定義函數 hitTestRectangle來檢查任何兩個矩形Pixi sprites是否接觸。

hitTestRectangle(spriteOne, spriteTwo)


如果它們重疊,hitTestRectangle將返回true。您可以使用hitTestRectangle與if語句來檢查兩個精靈這樣的之間的衝突:
if (hitTestRectangle(cat, box)) {
//There's a collision
} else {
//There's no collision
}

正如你將看到的,hitTestRectangle是進入龐大宇宙的遊戲設計的前門。

在collisionDetection.html文件examples夾中運行該文件,獲取如何使用的工作示例hitTestRectangle。使用箭頭鍵移動貓。如果貓碰到盒子,盒子變紅,“打!由文本對象顯示。


[img]http://dl2.iteye.com/upload/attachment/0123/3480/e593d90c-7e24-35a8-ba58-4bd4f82a0369.png[/img]

你已經看到了創建所有這些元素的所有代碼,以及使貓移動的鍵盤控制系統。唯一新的東西是在函數hitTestRectangle內部使用的方式play來檢查衝突。


function play() {

//use the cat's velocity to make it move
cat.x += cat.vx;
cat.y += cat.vy;

//check for a collision between the cat and the box
if (hitTestRectangle(cat, box)) {

//if there's a collision, change the message text
//and tint the box red
message.text = "hit!";
box.tint = 0xff3300;

} else {

//if there's no collision, reset the message
//text and the box's color
message.text = "No collision...";
box.tint = 0xccff99;
}
}


因爲該play函數每秒由遊戲循環調用60次,所以這個if語句不斷地檢查cat和box之間的衝突。如果hitTestRectangle是true,文本message對象用於setText顯示“Hit”:

message.text = "hit!";


然後通過將框的tint屬性設置爲十六進制紅色值,將框的顏色從綠色更改爲紅色。

box.tint = 0xff3300;

如果沒有衝突,消息和框保持在其原始狀態:

message.text = "no collision...";
box.tint = 0xccff99;


這段代碼很簡單,但是突然間,你創建了一個似乎完全活躍的互動世界。它幾乎像魔術!也許,令人驚訝的是,你現在有所有你需要的技能開始製作遊戲與Pixi!

hitTestRectangle函數

但是hitTestRectangle功能怎麼樣?它做什麼,它是如何工作的?關於如何工作的碰撞檢測算法的細節略微超出了本教程的範圍。最重要的是你知道如何使用它。但是,僅供參考,如果你好奇,這裏是完整的 hitTestRectangle函數定義。你能從評論中知道它在做什麼嗎?


function hitTestRectangle(r1, r2) {

//Define the variables we'll need to calculate
var hit, combinedHalfWidths, combinedHalfHeights, vx, vy;

//hit will determine whether there's a collision
hit = false;

//Find the center points of each sprite
r1.centerX = r1.x + r1.width / 2;
r1.centerY = r1.y + r1.height / 2;
r2.centerX = r2.x + r2.width / 2;
r2.centerY = r2.y + r2.height / 2;

//Find the half-widths and half-heights of each sprite
r1.halfWidth = r1.width / 2;
r1.halfHeight = r1.height / 2;
r2.halfWidth = r2.width / 2;
r2.halfHeight = r2.height / 2;

//Calculate the distance vector between the sprites
vx = r1.centerX - r2.centerX;
vy = r1.centerY - r2.centerY;

//Figure out the combined half-widths and half-heights
combinedHalfWidths = r1.halfWidth + r2.halfWidth;
combinedHalfHeights = r1.halfHeight + r2.halfHeight;

//Check for a collision on the x axis
if (Math.abs(vx) < combinedHalfWidths) {

//A collision might be occuring. Check for a collision on the y axis
if (Math.abs(vy) < combinedHalfHeights) {

//There's definitely a collision happening
hit = true;
} else {

//There's no collision on the y axis
hit = false;
}
} else {

//There's no collision on the x axis
hit = false;
}

//`hit` will be either `true` or `false`
return hit;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章