I am making a top view medieval game using HTML, JS and canvas.
The problem is that my player is able to hit to others when not looking at them. I made a condition in the third line in the below code to address this problem, but that is not working because the player's look angle limits are max 180
and min -180
. The limits between the player's position and victim's position are max 90
min -270
. These limits ruin my condition.
I can accept any ideas or readymade condition or code.
if(Math.sqrt(Math.pow((this.X-Victim.X),2),Math.pow((this.Y-Victim.Y),2)) <= 100){//<-here calculates distance between victim and player
var angle = Math.atan2(this.X - Victim.X , this.Y - Victim.Y) * (180 / Math.PI);//<-here calculates angle between victim and player
if((angle < this.LookAngle + 45)&&(angle > this.LookAngle - 45)){//<- i need help on here
console.log(angle,this.LookAngle);
//socket.emit('HitTo',{UserName:Victim.UserName,hitval:20});//<- actually you dont need to know this
}
}
answering my own question
first i will flip my angle vertically because its must be reverse. go to source
180-angle
then i must convert the (look angle) and (angle between 2 player) to 0-360. go to source
(angle + 360) % 360
then i need to check the angle between in other two angle. go to source
var isbetween = (startangle,midangle,endangle) => {
endangle = (endangle- startangle) < 0 ? endangle - startangle + 360 : endangle - startangle;
midangle = (midangle - startangle) < 0 ? midangle - startangle + 360 : midangle- startangle;
return (midangle < endangle);
}
and applying to my code
if(Math.sqrt(Math.pow((this.X-Victim.X),2),Math.pow((this.Y-Victim.Y),2)) <= 100){
var angle = Math.atan2(this.X - Victim.X , this.Y - Victim.Y) * (180 / Math.PI);
var flippedangle = 180 - angle;
var fixedangle = (flippedangle + 360) % 360;
var fixedlook = (this.LookAngle + 360) % 360;
if(((fixedangle - (fixedlook + 80)) < 0 ? fixedangle - (fixedlook + 80) + 360 : fixedangle - (fixedlook + 80)) > (((fixedlook - 80) - (fixedlook + 80)) < 0 ? (fixedlook - 80) - (fixedlook + 80) + 360 : (fixedlook - 80) - (fixedlook + 80))){
socket.emit('HitTo',{UserName:Victim.UserName,hitval:20});
}
}
Thank you
Or if that isn't helping, one of the answers from Stack Overflow found by searching for "javascript check if two angles are close" should give you enough useful information to solve it. – Andrew Morton