Jump to content

Changing pictures on HTML5 game when arrow moves left


Recommended Posts

Hi. I'm trying to move my space jet so that way it is facing the left when I move the arrow key left, and it is facing right when I move the arrow key right. Any help would be greatly appreciated. Thanks. Here's my code in Javascript: 

 

var canvasBg = document.getElementById('canvasBg');var ctxBg = canvasBg.getContext('2d');var canvasJet = document.getElementById('canvasJet');var ctxJet = canvasJet.getContext('2d');var jet1;var gameWidth = canvasBg.width;var gameHeight = canvasBg.height;	var fps = 10;var drawInterval;var imgSprite = new Image();imgSprite.src = 'sprite.png';imgSprite.addEventListener('load',init,false);//MAIN FUNCTIONSfunction init() {	drawBg();	startDrawing();	jet1 = new Jet();	document.addEventListener('keydown',checkKeyDown,false);	document.addEventListener('keyup',checkKeyUp,false);}function draw() {		jet1.draw();}function startDrawing() {	stopDrawing();	drawInterval = setInterval(draw,fps);	}function stopDrawing() {	clearInterval(drawInterval);}function drawBg() {		var srcX = 0;		var srcY = 0;		var drawX = 0;		var drawY = 0;		ctxBg.drawImage(imgSprite,srcX,srcY,gameWidth,gameHeight,drawX,drawY,gameWidth,gameHeight);	}function clearCtxBg() {	ctxBg.clearRect(0,0,gameWidth,gameHeight);	}//END OF MAIN FUNCTIONS//Jet functionsfunction Jet() {	this.srcX = 0;	this.srcY = 500;	this.drawX = 200;	this.drawY = 200;	this.width = 100;	this.height = 50;	this.speed = 2;	this.isUpKey = false;	this.isRightKey = false;	this.isDownKey = false;	this.isLeftKey = false;}Jet.prototype.draw = function () {		clearCtxJet();			this.checkKeys();		ctxJet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);	};Jet.prototype.checkKeys = function () {		if(this.isUpKey) {		this.drawY -= this.speed;	}		if(this.isRightKey) {		this.drawX += this.speed;	}		if(this.isDownKey) {		this.drawY += this.speed;	}		if(this.isLeftKey) {		this.drawX -= this.speed;	}};function clearCtxJet() {	ctxJet.clearRect(0,0,gameWidth,gameHeight);	}//END JET FUNCTIONS//EVENT FUNCTIONSfunction checkKeyDown(e) {		var keyID =  e.keyCode || e.which;		/// === mean exactly equal to		/// || mean 'OR'.		if (keyID === 38 || keyID === 87) { //38 means up arrow key and 87 means 'W' key.			jet1.isUpKey = true;			// prevent page from srcolling			e.preventDefault();	 		}		if (keyID === 39 || keyID === 68) { //38 means up arrow key and 87 means 'W' key.			jet1.isRightKey = true;			// prevent page from srcolling			e.preventDefault();	 		}		if (keyID === 40 || keyID === 83) {	 //38 means up arrow key and 87 means 'W' key.			jet1.isDownKey = true;			// prevent page from srcolling			e.preventDefault();	 		}		if (keyID === 37 || keyID === 65) { //let arrow or A key			jet1.isLeftKey = true;			// prevent page from srcolling			e.preventDefault();	 		}}function checkKeyUp(e) {		var keyID =  e.keyCode || e.which;		/// === mean exactly equal to		/// || mean 'OR'.		if (keyID === 38 || keyID === 87) { //38 means up arrow key and 87 means 'W' key.			jet1.isUpKey = false;			// prevent page from srcolling			e.preventDefault();					}		if (keyID === 39 || keyID === 68) { //38 means up arrow key and 87 means 'W' key.			jet1.isRightKey = false;			// prevent page from srcolling			e.preventDefault();	 		}		if (keyID === 40 || keyID === 83) {	 //38 means up arrow key and 87 means 'W' key.			jet1.isDownKey = false;			// prevent page from srcolling			e.preventDefault();	 		}		if (keyID === 37 || keyID === 65) { //let arrow or A key			jet1.isLeftKey = false;			// prevent page from srcolling			e.preventDefault();	 		}}//END OF EVENT FUNCTIONS

 

Link to post
Share on other sites

You can use canvas.translate and canvas.rotate to rotate the ship to face the desired direction.

 

function Jet() {	this.srcX = 0;	this.srcY = 500;	this.drawX = 200;	this.drawY = 200;	this.width = 100;	this.height = 50;	this.speed = 2;	this.isUpKey = false;	this.isRightKey = false;	this.isDownKey = false;	this.isLeftKey = false;	this.rotation = 0;   // Keep track of the rotation} Jet.prototype.draw = function () {		clearCtxJet();			this.checkKeys();                                // Get the x,y position of the center of the ship		var centerX = this.drawX + (this.width / 2);		var centerY = this.drawY + (this.height / 2);		ctxJet.save();  // Save the current state of the canvas		ctxJet.translate(centerX , centerY);  // Translate the origin of the canvas to the center of the ship		ctxJet.rotate(this.rotation * Math.PI / 180);   // Rotate the canvas this.rotation degrees around the center of the ship		ctxJet.translate(-centerX, -centerY);   // Translate back to the original origin 		ctxJet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);  // Draw as normal		ctxJet.restore();  // Restore the state}; Jet.prototype.checkKeys = function () {		if(this.isUpKey) {		this.rotation = 0;  // Up = 0 degrees		this.drawY -= this.speed;	}		if(this.isRightKey) {		this.rotation = 90;  // Right = 90 degrees		this.drawX += this.speed;	}		if(this.isDownKey) {		this.rotation = 180;  // Down = 180 degrees		this.drawY += this.speed;	}		if(this.isLeftKey) {		this.rotation = 270;  // Left = 270 degrees		this.drawX -= this.speed;	}};
Link to post
Share on other sites

It doesn't work. Here's my code with your code in it:

 

var canvasBg = document.getElementById('canvasBg');var ctxBg = canvasBg.getContext('2d');var canvasJet = document.getElementById('canvasJet');var ctxJet = canvasJet.getContext('2d');var jet1;var gameWidth = canvasBg.width;var gameHeight = canvasBg.height;	var fps = 10;var drawInterval;var imgSprite = new Image();imgSprite.src = 'sprite.png';imgSprite.addEventListener('load',init,false);//MAIN FUNCTIONSfunction init() {	jet1 = new Jet();	drawBg();	startDrawing();	document.addEventListener('keydown',checkKeyDown,false);	document.addEventListener('keyup',checkKeyUp,false);}function draw() {		jet1.draw();}function startDrawing() {	stopDrawing();	drawInterval = setInterval(draw,fps);	}function stopDrawing() {	clearInterval(drawInterval);}function drawBg() {		var srcX = 0;		var srcY = 0;		var drawX = 0;		var drawY = 0;		ctxBg.drawImage(imgSprite,srcX,srcY,gameWidth,gameHeight,drawX,drawY,gameWidth,gameHeight);	}function clearCtxBg() {	ctxBg.clearRect(0,0,gameWidth,gameHeight);	}function Jet() {	this.srcX = 0;	this.srcY = 500;	this.drawX = 200;	this.drawY = 200;	this.width = 100;	this.height = 50;	this.speed = 2;	this.isUpKey = false;	this.isRightKey = false;	this.isDownKey = false;	this.isLeftKey = false;	this.rotation = 0;   // Keep track of the rotation} Jet.prototype.draw = function () {		clearCtxJet();			this.checkKeys();                                // Get the x,y position of the center of the ship		var centerX = this.drawX + (this.width / 2);		var centerY = this.drawY + (this.height / 2); 		ctxJet.save();  // Save the current state of the canvas		ctxJet.translate(centerX , centerY);  // Translate the origin of the canvas to the center of the ship		ctxJet.rotate(this.rotation * Math.PI / 180);   // Rotate the canvas this.rotation degrees around the center of the ship		ctxJet.translate(-centerX, -centerY);   // Translate back to the original origin 		ctxJet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);  // Draw as normal		ctxJet.restore();  // Restore the state}; Jet.prototype.checkKeys = function () {		if(this.isUpKey) {		this.rotation = 0;  // Up = 0 degrees		this.drawY -= this.speed;	}		if(this.isRightKey) {		this.rotation = 90;  // Right = 90 degrees		this.drawX += this.speed; 	}		if(this.isDownKey) {		this.rotation = 180;  // Down = 180 degrees		this.drawY += this.speed;	}		if(this.isLeftKey) {		this.rotation = 270;  // Left = 270 degrees		this.drawX -= this.speed;	}};
Link to post
Share on other sites

When you say it doesn't work, what exactly doesn't work? Does the image not rotate the correct direction (check the rotation degrees)? Maybe it rotates but it doesn't rotate around the center (in which case your width and height of the ship need to match that of the image)? If nothing is showing up, check the error console for JavaScript errors and try to resolve those.

Link to post
Share on other sites

Hi. I'm trying to move my space jet so that way it is facing the left when I move the arrow key left, and it is facing right when I move the arrow key right. Any help would be greatly appreciated. Thanks. Here's my code in Javascript: 

 

Do you have public page with your original attempt on it? I'm interested in seeing the sprite. And by the way, is this a side scrolling or top down perspective?

Link to post
Share on other sites

When you say it doesn't work, what exactly doesn't work? Does the image not rotate the correct direction (check the rotation degrees)? Maybe it rotates but it doesn't rotate around the center (in which case your width and height of the ship need to match that of the image)? If nothing is showing up, check the error console for JavaScript errors and try to resolve those.

It's just the sprite background.  I checked my .css and .html files, everything is correct. must be Javascript. When I check for errors, Uncaught ReferenceError: checkKeyDown is not defined

443Uncaught ReferenceError: clearCtxJet is not defined gameo.js:71
550
  1. Uncaught ReferenceError: clearCtxJet is not defined
Link to post
Share on other sites

Since this it's a side scrolling perspective you're probably not going to want to rotate the sprite of your jet. On your sprite there should be a jet facing right and one facing left. If there isn't then you need to get one on there. Then when you detect that the facing direction has changed you need to update your jet's srcX and srcY to show the correct image on the sprite that corresponds with that direction.

 

Then in code you need to update the jet's srcX and srcY inside the part that you're detecting left and right keys. Similar to this:

		if (keyID === 39 || keyID === 68) {			// set key value			jet1.isRightKey = true;			// update sprite location			jet1.srcX = 0;			jet1.srcY = 500;			// prevent page from srcolling			e.preventDefault();	 		} 		if (keyID === 37 || keyID === 65) {			// set key value			jet1.isLeftKey = true;			// update sprite location			jet1.srcX = ??; // you need to figure this out			jet1.srcY = ??; // you need to figure this out			// prevent page from srcolling			e.preventDefault();		}
Link to post
Share on other sites

I was thinking that's what I needed to do, but I thought I could just code it out instead of creating a left facing jet. Wouldn't I need to change some code in my functions though to make it work when I hit the left arrow key? 

 

I'll go and create my jet facing the opposite direction. Thanks for that.

Link to post
Share on other sites

When I move the arrow keys, it shows up white.

 

function checkKeyDown(e) {    var keyID = e.keyCode || e.which;    if (keyID === 38 || keyID === 87) { //up arrow or W key        jet1.isUpKey = true;        e.preventDefault();    }    if (keyID === 39 || keyID === 68) { //right arrow or D key        jet1.isRightKey = true;        e.preventDefault();    }    if (keyID === 40 || keyID === 83) { //down arrow or S key        jet1.isDownKey = true;        e.preventDefault();    }    if (keyID === 37 || keyID === 65) { //left arrow or A key        jet1.isLeftKey = true;				// update sprite location			jet1.srcX = 42; // you need to figure this out			jet1.srcY = 142; // you need to figure this out			        e.preventDefault();    }}function checkKeyUp(e) {    var keyID = e.keyCode || e.which;    if (keyID === 38 || keyID === 87) { //up arrow or W key        jet1.isUpKey = false;        e.preventDefault();    }    if (keyID === 39 || keyID === 68) { //right arrow or D key        jet1.isRightKey = false;        e.preventDefault();    }    if (keyID === 40 || keyID === 83) { //down arrow or S key        jet1.isDownKey = false;        e.preventDefault();    }    if (keyID === 37 || keyID === 65) { //left arrow or A key		// update sprite location			jet1.srcX = 42; // you need to figure this out			jet1.srcY = 146; // you need to figure this out			        jet1.isLeftKey = false;        e.preventDefault();    }}
Link to post
Share on other sites
  • 2 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...