2016-12-13 12 views
0

私は、敵のアグロ検出のための円形の検出領域をコードするのに苦労しています。現在、プレイヤーのxとyの位置が、敵のxとyの位置プラスとマイナスのaggroDistに衝突すると、敵は引き出されます。ここ円形敵アグロ状態? (純粋なJSの2Dゲーム)

は、現在のコードである。このアプローチに

if (player.x > enemies[e].x -enemies[e].aggroDist && 
    player.x < enemies[e].x +enemies[e].aggroDist && 
    player.y > enemies[e].y -enemies[e].aggroDist && 
    player.y < enemies[e].y +enemies[e].aggroDist) { 
     enemies[e].isAggro = true; 
     console.log(enemies[e].isAggro); 
    } 

問題敵が対角線エッジに遠い距離にプレイヤーを検出することができることを意味し、正方形状の検出領域です。

enter image description here

私はenemies[e].x + (enemies[e].aggroDist * Math.PI)のようなものを使用して円形の検知エリアを作ってみましたが、私は(このアプローチはあまりにも間違っているかもしれないので)それを実装する方法は考えています。

どのように私は検出領域の中心とその境界の間のすべての距離を厳密に同じにすることができますか?ここで

+0

あなたは赤い点が円の内側にあるかどうかを知りたいですか? –

+0

['Math.hypot(dx、dy)'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot)( "ピタゴラス定理"を検索するか、 "distance formula") – qxz

+0

各エンティティの中心点からの距離を "aggroDist"として使用できますか? http://www.purplemath.com/modules/distform.htm –

答えて

1

は、距離の式を使用して大まかな実装です:

//Load HTML elements 
 
var c = document.getElementById("c"); 
 
var ctx = c.getContext("2d"); 
 
//Distance function 
 
function distance(x1, y1, x2, y2) { 
 
    return Math.sqrt((x2 -= x1) * x2 + (y2 -= y1) * y2); 
 
} 
 
//Entity is the player, radius is the aggro distance 
 
var entity = { x: 200, y: 200, radius: 50 }; 
 
//Radius is the aggro distance of the other entities 
 
var radius = 2; 
 
//Draw player 
 
ctx.beginPath(); 
 
ctx.arc(entity.x, entity.y, entity.radius, 0, 2 * Math.PI); 
 
ctx.stroke(); 
 
ctx.closePath(); 
 
//Loop through "X" and "Y" combinations and draw "enemies" 
 
for (var x = 0; x < 400; x += 10) { 
 
    for (var y = 0; y < 400; y += 10) { 
 
     //Get distance between "enemy" and "player" 
 
     var d = distance(x, y, entity.x, entity.y); 
 
     //If the distance is less than the combined aggro distances, turn red, else turn green 
 
     ctx.strokeStyle = (d < entity.radius + radius ? "red" : "green"); 
 
     //Draw enemy 
 
     ctx.beginPath(); 
 
     ctx.arc(x, y, radius, 0, 2 * Math.PI); 
 
     ctx.stroke(); 
 
     ctx.closePath(); 
 
    } 
 
}
<canvas id="c" height="400" width="400"></canvas>

+0

非常に洗練されたソリューションで、魅力的な作品です!ありがとうございました ! –