I'm having trouble with my game movement. I have either incorrectly used sin and cos to calculate the true X,Y to move the screen (character stays centered) or the calculation takes too long and doesn't refresh fast enough. The below code is implemented in a game loop that uses window.requestAnimationFrame to continue looping.
Sometimes it moves in the right direction and sometimes it moves in the opposite of what I would expect, but this behavior is not consistent.
My angles range in both positive and negative (0-360) depending if the avatar is turning clockwise or counter (this part of the code registers correctly). I have tested battleField object set methods to make sure they correctly set the top and left. I have tested battleField object methods to make sure it returns the correct top and left values (in integer, no unit indicator like 'px');
Any thoughts or suggestions are much appreciated.
let battleField = {
id: 'battleField',
speed: 5,
get speedTop() {
let rotateNum = parseInt(rotateAngle,10);
let radians=rotateNum*Math.PI/180
let trueTop=userAvatar.speed*(Math.sin(radians))
return trueTop;
},
get speedLeft() {
let rotateNum = parseInt(rotateAngle,10);
let radians=rotateNum*Math.PI/180
let trueLeft=userAvatar.speed*(Math.cos(radians))
return trueLeft
},
get element() {
let elm = document.getElementById(this.id);
return elm;
},
get bottom() {
let elmBottom = parseInt(window.getComputedStyle(this.element).bottom, 10);
return elmBottom;
},
get top() {
let elmTop = parseInt(window.getComputedStyle(this.element).top, 10);
return elmTop;
},
get left() {
let elmLeft = parseInt(window.getComputedStyle(this.element).left, 10);
return elmLeft;
},
get right() {
let elmRight = this.left + this.width;
return elmRight;
},
get width() {
let elmWidth = parseInt(window.getComputedStyle(this.element).width, 10);
return elmWidth;
},
get height() {
let elmHeight = parseInt(window.getComputedStyle(this.element).height, 10);
return elmHeight;
},
set setBottom(value) {
this.element.style.bottom = value + 'px';
},
set setLeft(value) {
this.element.style.left = value + 'px';
},
set setRight(value) {
this.element.style.left = (value - 50) + 'px';
},
set setTop(value) {
this.element.style.top = (value) + 'px';
},
get maxRight() {
if(this.left<screenArea.width-this.width){
return true;
}
},
get maxLeft() {
if(this.left>=0){
return true;
}
},
get maxTop() {
if(this.top>=0){
return true;
}
},
get maxBottom() {
if(this.top<screenArea.height-this.height){
return true;
}
}
}
let userAvatar = {
speed:5
}
let rotateAngle="15deg";
function loop(){
let rotateNum = parseInt(rotateAngle,10);
let radians=rotateNum*Math.PI/180
let newTop= battleField.top + (Math.sin(radians) * userAvatar.speed);
let newLeft= battleField.left - (Math.cos(radians) * userAvatar.speed);
battleField.setTop = newTop;
battleField.setLeft = newLeft;
window.requestAnimationFrame(loop);
}
window.requestAnimationFrame(loop);