Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript player movement

//Javascript game template
//Move player with arrow keys

var canvas = document.createElement("canvas");
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");

var player = {x: canvas.width / 2, y: canvas.height / 2, speed: 10};
var keys = [];

function update() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.fillRect(player.x, player.y, 50, 50);
  
  if (keys[37])
    player.x -= player.speed;
  if (keys[38])
    player.y -= player.speed;
  if (keys[39])
    player.x += player.speed;
  if (keys[40])
    player.y += player.speed;
  
  requestAnimationFrame(update);
}
update();

document.onkeydown = function(e) {
  keys[e.keyCode] = true;
}
document.onkeyup = function(e) {
  keys[e.keyCode] = false;
}
Comment

javascript player movement

Jet.prototype.checkDirection = function () {
if (this.isUpKey) {
    this.drawY -= this.speed;
    if (this.speed < 5) {
        this.speed += 0.1;
    }
}
if (this.isDownKey) {
    this.drawY += this.speed;
    if (this.speed < 5) {
        this.speed += 0.1;
    }
}
if (!this.isUpKey) {
    if (!this.isDownKey) {
        if (this.speed >= 0) {
            this.drawY -= this.speed;
            this.speed -= 1;
        }
    }
}
if (!this.isDownKey) {
    if (!this.isUpKey) {
        if (this.speed >= 0) {
            this.drawY += this.speed;
            this.speed -= 1;
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: swift encode json 
Javascript :: javascript cookies vs session vs local storage 
Javascript :: dynamic forms in react 
Javascript :: setinterval() nodejs 
Javascript :: setTimeout(() = { console.log(i);}, 100); 
Javascript :: javscript rename property name 
Javascript :: callback without duplicates javascript 
Javascript :: javascript mutation observer 
Javascript :: how to check characters inside a string javascript 
Javascript :: react-native-popup-menu 
Javascript :: get file extension in javascript 
Javascript :: sort in array in javascript 
Javascript :: mock callback function jest 
Javascript :: angularjs make post request 
Javascript :: how to check if string contains substring javascript 
Javascript :: how to create a javascript hello world program with node.js 
Javascript :: react native update state array of objects 
Javascript :: javascript fetch 
Javascript :: date object js 
Javascript :: filter object array 
Javascript :: useLocation for query params 
Javascript :: React social login button 
Javascript :: javascript select audio device 
Javascript :: Searchkick::ImportError: {"type"="cluster_block_exception" 
Javascript :: hincrby nodejs 
Javascript :: ways of defining object js 
Javascript :: key js 
Javascript :: react router dom default params 
Javascript :: js map delete item 
Javascript :: get max number in array 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =