I want to control the amount of times draw() is being called, basically lets immagine that i have that basic code:
var e = 1;
function setup() {
window.canvas = createCanvas(200, 200);
}
function draw() {
fill(255, 255, 0);
ellipse(50 + e, 50, 30);
e++;
}
and I want to make a function moveOneStep() that will active draw() once, so let's assume I'm doing a for loop 5 times, then draw will be called 5 times and the circle will move 5 steps ( pixels ) to the right,
how can it be done?
Do you want to fixe the framerate in your code or to call draw() function in a specific time? If it's the case I don't think you can because the draw function is, as mentioned in the documentation
the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called
But if you want to fixe the frame rate u can call the frameRate(number) in the setup() function. So, now if you want to have draw() called 30 times per second
(or 30 fps for a gaming reference) your code will look like this.
var e = 1;
function setup() {
window.canvas = createCanvas(200, 200);
frameRate(30);
}
function draw() {
fill(255, 255, 0);
ellipse(50 + e, 50, 30);
e++;
}
Check the dcumentation for further references.
Happy coding ^^.
Instead of controlling the number of times that draw gets called you can control what happens inside of draw.
To use draw in a way that allows user interaction and works well with the p5js lib you can listen for user interaction with a keyPressed method and record what the user is telling the system to do. Back in the draw method you can update positions and then render the sketch.
This approach breaks the direct connection between frame rate and user interaction. For example we could slow the frame rate down but still allow the user to click buttons as quickly as the key board would allow. Positions would still get adjusted and draw would catch up.
Here is a simple example that allows a user to move a circle with a ,s, d, w keys or up, down, left, right arrow keys.
var xPos = 0;
var yPos = 0;
var moveRightCount = 0;
var moveLeftCount = 0;
var moveUpCount = 0;
var moveDownCount = 0;
function setup() {
window.canvas = createCanvas(200, 200);
}
function keyPressed() {
if (keyCode === RIGHT_ARROW || keyCode === 68) {
moveRightCount+=1;
} else if (keyCode === LEFT_ARROW || keyCode === 65) {
moveLeftCount+=1;
} else if (keyCode === DOWN_ARROW || keyCode === 83) {
moveDownCount+=1;
}else if (keyCode === UP_ARROW || keyCode === 87) {
moveUpCount+=1;
} else if (keyCode === 70){
// console.log(keyCode);
}
function draw() {
background(255);
if (moveRightCount > 0){
xPos++;
moveRightCount--;
}
if (moveLeftCount > 0){
xPos--;
moveLeftCount--;
}
if (moveUpCount > 0){
yPos--;
moveUpCount--;
}
if (moveDownCount > 0){
yPos++;
moveDownCount--;
}
fill(255, 255, 0);
ellipse(50 + xPos, 50 + yPos, 30);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
Now if you have a method called moveOneStep() it could adjust the appropriate move count and as draw gets called according to its frameRate the image would be moved. Say we call moveOneStep() in a loop that executes 5 times the image would be moved one position per execution of draw 5 times.
Related
I'm pretty sure after looking through the documentation that this isn't what the framework is intended to do, but I've got a student I'm tutoring who really wants to move an object drawn on a P5 canvas using input, like using the arrow keys.
What I was able to figure out is the following:
let value = 0;
function setup() {
// Create a canvas with a specified width and height
createCanvas(400, 400);
// Fill in background color
background("blue");
}
function draw() {
background(200);
rectMode(CENTER);
translate(value, value, value);
translate(150, 150, 150)
rect(0, 0, 20, 20);
}
function keyPressed() {
while(true) {
if (keyCode == LEFT_ARROW) {
value = 20;
}
}
}
But of course, this uses an infinite loop and is therefore less than ideal. Does anyone know of a better way to achieve this?
On my system (Chrome, MacOS), keyPressed is called repeatedly if I hold the left-arrow key. Below is a really simple example. Focus into the snippet and hold down your left arrow key - observe that the xPos decreases every frame.
You need to actually do something in your keyPressed method. Right now, the value is just being assigned repeatedly, and definitely, you don't want to have an infinite loop.
For the record, according to the docs, keyPressed isn't guaranteed to work this way on all systems, so you may need more complex logic depending on what system(s) you want to run this on.
function setup() {
createCanvas(640, 360);
}
let xPos = 100;
function draw() {
background(0,0,255);
fill(255,0,0);
ellipse(xPos,50,10,10);
}
function keyPressed(event) {
if (keyCode == LEFT_ARROW) {
xPos -= 1;
} else if (keyCode == RIGHT_ARROW) {
xPos += 1;
}
// this prevents default browser behavior
event.preventDefault();
return false;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/p5.js/0.3.3/p5.min.js"></script>
let acl;
let pos;
let value = 0;
function setup() {
acl = createVector(0,0);
pos = createVector(0,0);
// Create a canvas with a specified width and height
createCanvas(400, 400);
// Fill in background color
background("blue");
}
function draw() {
background(200);
rectMode(CENTER);
rect(pos.x, pos.y, 20, 20);
pos.add(acl);
}
function keyPressed() {
if (keyCode == LEFT_ARROW) {
acl.set(-1,0)
}
if(keyCode == RIGHT_ARROW){
acl.set(1,0)
}
}
I am creating a game, but I have an issue where i want to move the player left or right but when I press the button it only moves it left or right once and not continuously
var player 1 = new Player(width / 4)
function keyPressed() {
if (key === "d") {
player1.move(1);
} else if (key === "a") {
player1.move(-1);
}
}
function Player(xPos) {
this.x = xPos;
this.y = height - 100;
this.show = function() {
fill(255);
rectMode(CENTER);
rect(this.x, this.y, 50, 100);
}
this.move = function(dir) {
this.x += dir * 5;
}
}
Use keyIsDown() instead of keyPressed().
From the documentation:
The keyIsDown() function checks if the key is currently down, i.e.
pressed. It can be used if you have an object that moves, and you want
several keys to be able to affect its behaviour simultaneously, such
as moving a sprite diagonally. You can put in any number representing
the keyCode of the key, or use any of the variable keyCode names
listed here.
Should also be inside the draw() function:
function draw(){
if(keyIsDown("d")){
player1.move(1);
}
if (keyIsDown("a")) {
player1.move(-1);
}
}
I am trying to make a game. The object of the game is to move the square across the screen without hitting a raindrop falling from the roof. How do i make it so that if one of the raindrops enters the square, the square returns to the beginning of the canvas or x =0. Here is the code:
var canvas = document.getElementById('game');
var ctx = canvas.getContext('2d');
var WIDTH = 1000;
var HEIGHT = 700;
var x = 0;
var y = HEIGHT-20;
var xPos = [0];
var yPos = [0];
var speed = [1];
var rainDrops = 50;
var rectWidth = 20;
var rectHeight = 20;
for (var i = 0; i < rainDrops; i++) {
xPos.push(Math.random()* WIDTH);
yPos.push(0);
speed.push(Math.random() * 5);
}
function rainFall () {
window.requestAnimationFrame(rainFall);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i = 0; i <rainDrops; i++) {
//Rain
ctx.beginPath();
ctx.arc(xPos[i], yPos[i], 3, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
//Rain movement
yPos[i]+=speed[i];
//Box
ctx.fillStyle = 'red';
ctx.fillRect(x, y, rectWidth, rectWidth);
if (yPos[i] > HEIGHT) {
yPos[i]= 0;
yPos[i]+=speed[0];
}
//This is the part where I need the Help!!!!!!!!!
if (){
x = 0;
}
}
};
//Move Object
function move (e) {
if (e.keyCode === 37) {
ctx.clearRect (0, 0, WIDTH, HEIGHT);
x -=10;
}
if (e.keyCode === 39) {
ctx.clearRect (0, 0, WIDTH, HEIGHT);
x+=10;
}
canvas.width=canvas.width
}
//Lockl Screen
window.addEventListener("keydown", function(e) {
// Lock arrow keys
if( [37,39,].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);
rainFall();
document.onkeydown = move;
window.addEventListener("load", doFirst, false);
Conditional statements
I am never too sure how to answer these types of questions. As you are a beginner I don't want to overwhelm you with code and techniques, but at the same time I don't want to give an answer that perpetuates some bad techniques.
The short answer
So first the simple answer from your code where you wrote
//This is the part where I need the Help!!!!!!!!!
// the test checks the center of the drop
// if drop is greater than > top of player (y) and (&&)
// drop x greater than > left side of player x and (&&) drop is less than <
// right side of player (x + rectWidth) then drop has hit player
if (yPos[i] > y && xPos[i] > x && xPos[i] < x + rectWidth ){
x = 0; // move player back
}
BTW you are drawing the player rectangle for each rain drop. You should move that draw function outside the loop.
The long answer
Hopefully I have not made it too confusing and have added plenty of comments about why I did this and that.
To help keep everything organised I separate out the various elements into their own objects. There is the player, rain, and keyboard handler. This is all coordinated via the mainLoop the is called once a frame (by requestAnimationFrame) and calls the various functions to do all that is needed.
The player object holds all the data to do with the player, and functions to draw and update the player (update moves the player)
The rain object holds all the rain in an array called rain.drops it has functions to draw and update the rain. It also has some functions to randomize a drop, and add new drops.
To test if the rain has hit the player I do it in the rain.update function (where I move the rain) I don`t know what you wanted to happen when the rain hits the player so I just reset the rain drop and added 1 to the hit counter.
I first check if the bottom of the rain drop drop.y + drop.radius is greater than the top of the player if(drop.y + drop.radius >= player.y){
This makes it so we dont waste time checking rain that is above the player.
The I test for the rain in the x direction. The easiest is the test the negative (if the rain is not hitting the player) as the logic is a little simplier.
If the right side of the drop is to the left of the left side of the player, or (use || for or) the left side of the drop is to the right of the right side of the player than the drop can not be hitting the player. As we want the reverse condition we wrap it in a brackets a put a not in front if(! ( ... ) )
The test is a little long so I break it into 2 lines for readability.
// drop is a single rain drop player is the player
if (drop.y + drop.radius >= player.y) {
if ( ! (drop.x + drop.radius < player.x ||
drop.x - drop.radius > player.x + player.width) ) {
// code for player hit by rain in here
}
}
The rain.update function also checks if the rain has hit the bottom of the canvas and resets it if so.
Demo
I copied your code from in the question and modified it.
addEventListener("load",function(){ // you had onload at the bottom after all the code that gets the canvas
// etc. Which kind of makes the on load event pointless. Though not needed
// in this example I have put it in how you can use it for a web page.
// Using onload event lets you put the javascript anywhere in the HTML document
// if you dont use onload you must then only put the javascript after
// the page elements you need eg Canvas.
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
ctx.font = "20px arial";
var frameCount = 0; // counts the frames
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var currentMaxDrops = 5; // rain will increase over time
const numberFramesPerRainIncrease = 60 * 5; // long name says it all. 60 frames is one second.
const maxRainDrops = 150; // max number of rain drops
// set up keyboard handler
addEventListener("keydown", keyEvent);
addEventListener("keyup", keyEvent);
requestAnimationFrame(mainLoop); // request the first frame of the animation (get it all going)
//==========================================================================================
// Setup the keyboard input stuff
const keys = { // list of keyboard keys to listen to by name.
ArrowLeft : false,
ArrowRight : false,
}
function keyEvent(event){ // the key event argument event.code hold the named key.
if(keys[event.code] !== undefined){ // is this a key we want
event.preventDefault(); // prevent default browser action
keys[event.code] = event.type === "keydown"; // true if keydown false if not
}
}
//==========================================================================================
const player = { // object for everything to do with the player
x : 0, // position
y : HEIGHT - 20,
width : 20, // size
height : 20,
speed : 4, // speed per frame
color : "red",
showHit : 0, // when this is > 0 then draw the player blue to indicate a hit.
// This counter is counted down each frame so setting its value
// determins how long to flash the blue
hitCount : 0, // a count of the number of drops that hit the player.
status(){ // uses hit count to get a status string
if(player.hitCount === 0){
return "Dry as a bone.";
}
if(player.hitCount < 5){
return "A little damp.";
}
if(player.hitCount < 15){
return "Starting to get wet.";
}
return "Soaked to the core";
},
draw(){ // draw the player
if(player.showHit > 0){
player.showHit -= 1; // count down show hit
ctx.fillStyle = "blue";
}else{
ctx.fillStyle = player.color;
}
ctx.fillRect(player.x,player.y,player.width,player.height);
},
update(){ // this updates anything to do with the player
// Not sure how you wanted movement. You had it so that you move only when key down events
// so I have done the same
if(keys.ArrowLeft){
player.x -= player.speed; // move to the left
keys.ArrowLeft = false; // turn off the key. If you remove this line then will move left while
// the key is down and stop when the key is up.
if(player.x < 0){ // is the player on or past left side of canvas
player.x = 0; // move player back to zero.
}
}
if(keys.ArrowRight){
player.x += player.speed; // move to the right
keys.ArrowRight = false; // turn off the key. If you remove this line then will move right while
// the key is down and stop when the key is up.
if(player.x + player.width >= WIDTH){ // is the player on or past right side of canvas
player.x = WIDTH - player.width; // move player back to inside the canvas.
}
}
}
}
//==========================================================================================
const rain = { // object to hold everything about rain
numberRainDrops : 50,
drops : [], // an array of rain drops.
randomizeDrop(drop){ // sets a drop to random position etc.
drop.x = Math.random() * WIDTH; // random pos on canvas
drop.y = -10; // move of screen a little so we dont see it just appear
drop.radius = Math.random() *3 + 1; // give the drops a little random size
drop.speed = Math.random() * 4 + 1; // and some speed Dont want 0 speed so add 1
return drop;
},
createDrop(){ // function to create a rain drop and add it to the array of drops
if(rain.drops.length < currentMaxDrops){ // only add if count is below max
rain.drops.push(rain.randomizeDrop({})); // create and push a drop. {} creates an empty object that the function
// randomizeDrop will fill with the starting pos of the drop.
rain.numberRainDrops = rain.drops.length;
}
},
draw(){ // draw all the rain
ctx.beginPath(); // start a new path
ctx.fillStyle = 'blue'; // set the colour
for(var i = 0; i < rain.drops.length; i ++){
var drop = rain.drops[i]; // get the indexed drop
ctx.arc(drop.x, drop.y, drop.radius, 0, 2 * Math.PI);
ctx.closePath(); // stops the drops rendered as one shape
}
ctx.fill(); // now draw all the drops.
},
update(){
for(var i = 0; i < rain.drops.length; i ++){
var drop = rain.drops[i]; // get the indexed drop
drop.y += drop.speed; // move down a bit.
if(drop.y + drop.radius >= player.y){ // is this drop at or below player height
// checks if the drop is to the left or right of the player
// as we want to know if the player is hit we use ! (not)
// Thus the next if statement is if rain is not to the left or to the right then
// it must be on the player.
if(!(drop.x + drop.radius < player.x || // is the rigth side of the drop left of the players left side
drop.x - drop.radius > player.x + player.width)){
// rain has hit the player.
player.hitCount += 1;
player.showHit += 5;
rain.randomizeDrop(drop); // reset this drop.
}
}
if(drop.y > HEIGHT + drop.radius){ // is it off the screen ?
rain.randomizeDrop(drop); // restart the drop
}
}
}
}
function mainLoop () { // main animation loop
requestAnimationFrame(mainLoop); // request next frame (don`t need to specify window as it is the default object)
ctx.clearRect(0, 0, WIDTH, HEIGHT);
frameCount += 1; // count the frames
// when the remainder of frame count and long name var is 0 increase rain drop count
if(frameCount % numberFramesPerRainIncrease === 0){
if(currentMaxDrops < maxRainDrops){
currentMaxDrops += 1;
}
}
rain.createDrop(); // a new drop (if possible) per frame
rain.update(); // move the rain and checks if the player is hit
player.update(); // moves the player if keys are down and check if play hits the side of the canvas
player.draw(); // draw player
rain.draw(); // draw rain after player so its on top.
ctx.fillStyle = "black";
ctx.fillText("Hit " + player.hitCount + " times.",5,20);
ctx.setTransform(0.75,0,0,0.75,5,34); // makes status font 3/4 size and set position to 5 34 so I dont have to work out where to draw the smaller font
ctx.fillText(player.status(),0,0); // the transform set the position so text is just drawn at 0,0
ctx.setTransform(1,0,0,1,0,0); // reset the transform to the default so all other rendering is not effected
};
});
canvas {
border : 2px black solid;
}
<canvas id="gameCanvas" width=512 height=200></canvas>
Hope this was helpfull.
Let's say we have a ball that can be moved left and right around the screen. When you click space, the ball should jump.
I got the ball to move left and right in a canvas. However, when the ball is moving left (for example) and I hit the space bar before anything, the ball stops moving left.
Check out my example so far!
I am using the KeyboardJS library to handle my key events:
KeyboardJS.on("left", function () {
cc();
x -= xv;
if (x < r) {
circle(x + width, y, r);
if (x + width <= width - r) {
x = x + width;
}
}
circle(x, y, r);
});
KeyboardJS.on("space", null, function () {
console.log("space!");
});
How could I get this behavior to stop so that when the space bar is hit, the ball jumps up but at the same time still moves to the left?
One thought added to everyone else's good ideas:
Separate your user input from your drawing.
Keyboarding:
If you’re having problems with KeyboardJS, check out Keydrown: http://jeremyckahn.github.io/keydrown/
Don’t do any drawing when capturing keys…just capture the user’s input of which direction they want the circle to go.
Set up an “direction” variable to hold how many times the user has pressed [left] or [right]:
var direction=0;
When [left] is pressed:
direction--;
When [right] is pressed:
direction++;
Direction is a net number. So if the user holds down the left key for 20 strokes and the right key for 15 strokes, direction will be -5 ( -20 + 15 ).
Set up an “altitude” variable to hold how many times the user has pressed [space]:
var altitude=0;
When [space] is pressed:
altitude-=10;
Altitude is a net number also.
Drawing:
Do all your drawing in a separate animation loop. Rather than using javascript’s setInterval, use the new and improved way of creating an imation loop -- requestAnimationFrame.
// set the starting circle positions
var currentX=canvas.width;
var currentY=canvas.height-r;
function animate(){
// even as we're executing this current animation loop
// request another loop for next time
requestAnimationFrame(animate);
// change the currentX position by the accumulated direction
currentX+=direction;
direction=0;
// change the currentY position by the accumulated altitude
currentY+=altitude;
altitude=0;
// draw the circle at its current position
cc();
circle(currentX,currentY,r);
// apply gravity to the circle
// to make it fall if its in the air
if(currentY<canvas.height-r){
currentY++;
}
}
Good Luck with your project!
What the problem is, is that if you press another key after pressing the first key, it will trigger that event, and stop triggering the other keydown event. This can be seen in this simplified example:
addEventListener('keydown',function(e) {console.log(e.keyCode, e.keyIdentifier)});
If you run that script, and then press left and then up, it will first show 37 Left a bunch of times, and then it'll show 32 U+0020 once and stop logging the left keydowns.
This is simply how the browser (and most other basic programs too) work. You can try doing the same thing in for example notepad, if you press the A key first, and then press space, it'll stop adding more As. This also means that you can't rely on key events (or key event libraries) to do this for you.
What you could do though, is make a global object that holds all keys that are pressed. For example:
window.KeysDown = {
37: false, //Left
39: false, //Right
38: false, //Up
40: false, //Down
32: false, //Space
};
addEventListener('keydown', function(e) {
var keyCode = e.keyCode||e.charCode||e.which;
if (keyCode == 32 && !window.KeysDown[keyCode])
onSpace();//This will only run when the spacebar is first pressed down.
if (window.KeysDown.hasOwnProperty(keyCode))
window.KeysDown[keyCode] = true;
});
addEventListener('keyup', function(e) {
var keyCode = e.keyCode||e.charCode||e.which;
if (window.KeysDown.hasOwnProperty(keyCode)) window.KeysDown[keyCode] = false;
});
var interval = setInterval(function() {
for (var i in window.KeysDown) {
if (window.KeysDown[i]) switch (i+'') {
case '37': onLeft(); break;
//case '38': window.KeysDown[i] && onUp(); break;
case '39': onRight(); break;
//case '40': window.KeysDown[i] && onDown(); break;
}
}
}, 50);
The syntax window.KeysDown[i] && onLeft() causes the onLeft function only to run if window.KeysDown[i] is true. I hope this solution works for you.
EDIT: I've changed the code to the working one. I've also made a JSFiddle that demonstrates this. The problem in my previous code was that apparently a switch doesn't handle integer values well, so I needed to convert i to a string.
EDIT: I've also added an extra part to the script that makes the onSpace function only run when the spacebar is first pressed down, and so that it won't run again until the spacebar is released and pressed again. I've also updated my JSFiddle to include these changes.
I would create a main function, which runs at a regular interval, and each time it runs, it updates the position of the circle based on what keys are currently down.
The main function can be done like this:
var keyDown = {};
function mainLoop() {
cc();
//pseudo code
if (keyDown["left"]) {
x -= 5;
}
if(keyDown["space"]) {
y -= 10;
}
// redraw circle at new location
circle(x,y,r);
}
setInterval(mainLoop, 30) //sets the function to be called every 30 milliseconds
// key event handler, first function handles the keydown, second function handles keyup
KeyboardJS.on("left", function() {
keyDown["left"] = true;
}, function() {
keyDown["left"] = false;
});
With this example, if the user had the left arrow key and space bar pressed when the mainLoop function ran, then the circle would move to the left 5 pixels, and up 10 pixels.
jsFiddle Demo
You are going to have to manually create a framework for this. KeyboardJS just wasn't cutting it. I guess I kind of set that up here. It uses an Action "class" coupled with key event triggers.
Action "class"
function Actions(){
this.count = 0;
this.running = {};
this.interval = undefined;
}
Actions.prototype.start = function(action){
if( typeof(this.running[action]) == "undefined"){
this[action]();
this.running[action] = action;
this.count++;
}
var me = this;
if( typeof(this.interval) == "undefined"){
this.interval = setInterval(function(){
for( var act in me.running ){
me[act]();
}
},50);
}
};
Actions.prototype.stop = function(action){
this.running[action] = void 0;
delete this.running[action];
this.count--;
if( this.count == 0 ){
clearInterval(this.interval);
this.interval = void 0;
};
};
Actions.prototype.left = function(){
cc();
x -= xv;
if (x < r) {
circle(x + width, y, r);
if (x + width <= width - r) {
x = x + width;
}
}
circle(x, y, r);
};
Actions.prototype.right = function(){
cc();
x += xv;
if (x >= width - r) {
circle((x - r) - (width - r), y, r);
if ((x - r) - (width - r) > r) {
x = (x - r) - (width - r);
}
}
circle(x, y, r);
};
Actions.prototype.space = function(){
cc();
y -= yv;
circle(x, y, r);
};
key event triggers
document.onkeydown = checkKeyDown;
function checkKeyDown(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left arrow
actions.start("left");
}
if (e.keyCode == '39') {
// right arrow
actions.start("right");
}
if (e.keyCode == '32') {
// space bar
actions.start("space");
}
}
document.onkeyup = checkKeyUp;
function checkKeyUp(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left arrow
actions.stop("left");
}
if (e.keyCode == '39') {
// right arrow
actions.stop("right");
}
if (e.keyCode == '32') {
// space bar
actions.stop("space");
}
}
Im currently working on getting my player sprite to move around my screen, but when a key is pressed all the sprite seems to do is disappear! I have no errors coming up in firebug, so i am assuming that the sprite isn't being redrawn correctly or something along those lines.
Here is my code for my player:
function Player()
{
var sprite = new Sprite(),
player,
x,
y,
w = sprite.width,
h = sprite.height,
speed = 4;
this.init_Player = function(pos_X, pos_Y){
player = sprite.load("player");
x = pos_X;
y = pos_Y;
};
this.update = function(delta) {
var calculated_speed = (speed * delta) * (60/1000);
$(document).keydown(function(e)
{
var cancel_default = (e.which === 32 || (e.which > 36 && e.which < 41));
cancel_default && e.preventDefault();
if(e.keyCode == 37){
x -=calculated_speed;
}
else if(e.keyCode == 38){
y -=calculated_speed;
}
else if(e.keyCode == 39){
x +=calculated_speed;
}
else if(e.keyCode == 40){
y +=calculated_speed;
}
});
};
this.draw = function() {
ctx.drawImage(player,x, y, w ,h);
};
}
The player is created in my main game javascript file like so:
player.init_Player(location_X,location_Y);
And then in my main game loop i have the now, delta and last times being made as well as the call to player.update and player.render like so:
function update(){
now = Date.now();
delta = now - last_update;
ctx.clearRect(0,0,canvas.width,canvas.height);
gameGUI.update();
player.update(delta);
player.draw();
last_update = now;
setTimeout(update,1);
}
Like i said at the top, all my sprite does on a key press is disappear. The code you can see above is all the code i have for the player so somewhere in here is the bug!
How would i accomplish making my sprite move on screen with a time-based animation like the one i've set up?
Thanks
EDIT
Also to let you know, i have last_update equal to Date.now() the line before my update call gets made initially like so:
function game_init(state) {
game_settings(state);
last_update = Date.now();
update();
}
Edit 2
On continued inspection, it doesn't seem like the sprite is disappearing after all, just moving very far e.i off the game screen... so another guess is that my calculations are wrong somewhere?
All sorted guys, i have my character moving using this little tutorial! Real easy to read and understand for the beginners out there.
LINK
What do the pros think of this tutorial?