Forward, Backward, Left and Right
This is a topic about realizing the movement function inside my pseudo-class for the Java Script application.
Here it is:
GameObject = function() {
this.x = 0;
this.y = 0;
this.cx = 0;
this.cy = 0;
this.w=20;
this.h=20;
this.pic='';
this.idx=0;
this.pics=[];
this.go=0;
this.right=[];
this.left=[];
this.up=[];
this.down=[];
this.frame=0;
this.delay=0;
this.sdelay=5;
this.ofx =0;
this.ofy =0;
this.go=0;
this.col=0;
this.IniArr =function(){
this.w=this.left[0].width;
this.h=this.left[0].height;
}
this.drawArr =function(spd){
if (frameCount % spd==0) this.idx++;
if (this.idx>this.right.length-1)this.idx=0;
if (this.go==0)
image(this.right[this.idx],this.x,this.y);
if (this.go==1)
image(this.left[this.idx],this.x,this.y);
if (this.go==2)
image(this.up[this.idx],this.x,this.y);
if (this.go==3)
image(this.down[this.idx],this.x,this.y);
if (this.go==4)
image(this.down[0],this.x,this.y);
}
this.loadImage =function(path){
var name = new Image();
name.src = path;
name.onload = function(){
}
return name;
}
this.checkcol=function(obj1,obj2){
var str=0;
if (obj1.x+obj1.w>obj2.x+this.ofx && obj1.x<(obj2.x+obj2.w+this.ofx )) {
if (obj1.y<(obj2.y+obj2.h)&& (obj1.y+obj1.h)>obj2.y){
str=1;
}
}
return str;
}
}
Some functions are added to make the class more convenient. I mean checking the collision function.
Here is an example of using class in P5JS
function setup() {
createCanvas(400, 400);
player.right[0]=loadImage("img/pr/1.png");
player.right[1]=loadImage("img/pr/2.png");
player.right[2]=loadImage("img/pr/3.png");
player.right[3]=loadImage("img/pr/4.png");
player.left[0]=loadImage("img/pl/1.png");
player.left[1]=loadImage("img/pl/2.png");
player.left[2]=loadImage("img/pl/3.png");
player.left[3]=loadImage("img/pl/4.png");
player.up[0]=loadImage("img/pu/1.png");
player.up[1]=loadImage("img/pu/2.png");
player.up[2]=loadImage("img/pu/3.png");
player.up[3]=loadImage("img/pu/4.png");
player.down[0]=loadImage("img/pd/1.png");
player.down[1]=loadImage("img/pd/2.png");
player.down[2]=loadImage("img/pd/3.png");
player.down[3]=loadImage("img/pd/4.png");
player.x=width/2-20;
player.y=height/2-20;
player.go=4;
}
function draw() {
background(220);
player.drawArr(4);
if(player.go==1)player.x=player.x-1;
if(player.go==0)player.x=player.x+1;
if(player.go==2)player.y=player.y-1;
if(player.go==3)player.y=player.y+1;
}
function keyPressed() {
if (keyCode === UP_ARROW) {
player.go=2;
} else if (keyCode === DOWN_ARROW) {
player.go=3;
}else if (keyCode === LEFT_ARROW) {
player.go=1;
}
else if (keyCode === RIGHT_ARROW) {
player.go=0;
}
return false; // prevent default
}
function keyReleased() {
player.go=4;
}
Here is an example -> https://editor.p5js.org/kirzh2020/present/5v-NTEaz7
Use Arrow Buttons to move hero on the screen
Comments
Post a Comment