Jump to content

how to control mousemove and keyboard movement


thatguy

Recommended Posts

Hi, I'm creating a game where the character moves across the bottom of the screen. Basically the keys move the character or the mouse does at the moment, but only by changing the code to do so. I want the character to move by either of them. when I try to use a Boolean it doesn't actually seem to check which one I'm using. So I'm wondering how to write this. Thanks in advance for any help! :)

I'll post the code as a comment below.

 

Link to comment
Share on other sites

(function(){//The canvasvar canvas = document.querySelector("canvas");//Create the drawing surface var drawingSurface = canvas.getContext("2d");//Arrays to store the game objects and assets to loadvar sprites = [];var assetsToLoad = [];var missiles = [];var aliens = [];var messages = [];//Create the backgroundvar background = Object.create(spriteObject);background.x = 0;background.y = 0;background.sourceY = 32;background.sourceWidth = 480;background.sourceHeight = 320;background.width = 480;background.height = 320;sprites.push(background);//Create the cannon and center itvar cannon = Object.create(spriteObject);cannon.x = canvas.width / 2 - cannon.width / 2;cannon.y = 280;sprites.push(cannon);var scoreDisplay02 = Object.create(messageObject);scoreDisplay02.font = "normal bold 30px emulogic";scoreDisplay02.fillStyle = "#00FF00";scoreDisplay02.x = 350;scoreDisplay02.y = 10;messages.push(scoreDisplay02);//Create the score messagevar scoreDisplay = Object.create(messageObject);scoreDisplay.font = "normal bold 30px emulogic";scoreDisplay.fillStyle = "#00FF00";scoreDisplay.x = 400;scoreDisplay.y = 10;messages.push(scoreDisplay);//The game over messagevar gameOverMessage = Object.create(messageObject);gameOverMessage.font = "normal bold 20px emulogic";gameOverMessage.fillStyle = "#00FF00";gameOverMessage.x = 70;gameOverMessage.y = 120;gameOverMessage.visible = false;messages.push(gameOverMessage);//Load the tilesheet imagevar image = new Image();image.addEventListener("load", loadHandler, false);image.src = "../images/alienArmada.png";assetsToLoad.push(image);//Load the soundsvar music = document.querySelector("#music");music.addEventListener("canplaythrough", loadHandler, false);music.load();assetsToLoad.push(music);var shootSound = document.querySelector("#shootSound");shootSound.addEventListener("canplaythrough", loadHandler, false);shootSound.load();assetsToLoad.push(shootSound);var mouseX = 0;canvas.style.cursor = "none";var explosionSound = document.querySelector("#explosionSound");explosionSound.addEventListener("canplaythrough", loadHandler, false);explosionSound.load();assetsToLoad.push(explosionSound);//Variable to count the number of assets the game needs to loadvar assetsLoaded = 0;var mouseX = cannon.x + cannon.halfWidth();canvas.addEventListener("mousemove", mousemoveHandler, false);canvas.addEventListener("mousedown", mousedownHandler, false);//Game statesvar LOADING = 0var PLAYING = 1;var OVER = 2;var gameState = LOADING;//Arrow key codesvar RIGHT = 39;var LEFT = 37;var SPACE = 32;//Directionsvar moveRight = false;var moveLeft = false;//Variables to help fire missilesvar shoot = false;var spaceKeyIsDown = false;//Game variablesvar score = 0;var scoreNeededToWin = 60;var alienFrequency = 100;var alienTimer = 0;function mousemoveHandler(event){   //Find the mouse's x and y position.  //Subtract the canvas's top and left offset  mouseX = event.pageX - canvas.offsetLeft;  mouseY = event.pageY - canvas.offsetTop;}function mousedownHandler(event){   //Create a bullet sprite fireMissile();}//Add keyboard listenerswindow.addEventListener("keydown", function(event){  switch(event.keyCode)  {	  case LEFT:	    moveLeft = true;	    break;  	    	  case RIGHT:	    moveRight = true;	    break;	 	  case SPACE:	    if(!spaceKeyIsDown)	    {	      shoot = true;	      spaceKeyIsDown = true;	    }   }}, false);window.addEventListener("keyup", function(event){  switch(event.keyCode)  {	    	  case LEFT:	    moveLeft = false;	    break;  	    	  case RIGHT:	    moveRight = false;	    break; 		  case SPACE:	    spaceKeyIsDown = false;  }}, false);//Start the game animation loopupdate();function update(){   //The animation loop  requestAnimationFrame(update, canvas);    //Change what the game is doing based on the game state  switch(gameState)  {    case LOADING:      console.log("loading…");      break;        case PLAYING:      playGame();      break;        case OVER:      endGame();      break;  }    //Render the game  render();}function loadHandler(){   assetsLoaded++;  if(assetsLoaded === assetsToLoad.length)  {    //Remove the load event listener from the image and sounds    image.removeEventListener("load", loadHandler, false);    music.removeEventListener("canplaythrough", loadHandler, false);    shootSound.removeEventListener("canplaythrough", loadHandler, false);    explosionSound.removeEventListener("canplaythrough", loadHandler, false);    console.log(assetsLoaded);    //Play the music    music.play();    music.volume = 0.3;        //Start the game     gameState = PLAYING;  }}function playGame(){  //Left  if(moveLeft && !moveRight)  {    cannon.vx = -8;  }  //Right  if(moveRight && !moveLeft)  {    cannon.vx = 8;  }  //Set the cannon's velocity to zero if none of the keys are being pressed  if(!moveLeft && !moveRight)  {    cannon.vx = 0;  }  //Fire a missile if shoot is true  if(shoot)  {    fireMissile();    shoot = false;	  }          //CODE BELOW FOR MOVEMENT HANDLER                  //if statement to control movement   if(keydown = false)  	{  		cannon.x = Math.max(0, Math.min(cannon.x + cannon.vx, canvas.width - cannon.width));  		  	}  	else           	{  		cannon.x = mouseX - (cannon.halfWidth());  	}        //I left both variances in the program as examples         object.onmousemove = function()  {  	cannon.x = mouseX - (cannon.halfWidth());  }  //if statement to control movement     	         //Move the missiles  for(var i = 0; i < missiles.length; i++)  {    var missile = missiles[i];    //Move it up the screen    missile.y += missile.vy;    //Remove the missile if it crosses the top of the screen    if(missile.y < 0 - missile.height)    {       //Remove the missile from the missiles array      removeObject(missile, missiles);      //Remove the missile from the sprites array      removeObject(missile, sprites);      //Reduce the loop counter by 1 to compensate       //for the removed element      i--;    }  }  //Make the aliens  //Add one to the alienTimer  alienTimer++;  //Make a new alien if alienTimer equals the alienFrequency  if(alienTimer === alienFrequency)  {    makeAlien();    alienTimer = 0;    //Reduce alienFrequency by one to gradually increase    //the frequency that aliens are created    if(alienFrequency > 2)    {        alienFrequency--;    }  }  //Loop through the aliens  for(var i = 0; i < aliens.length; i++)  {     var alien = aliens[i];    if(alien.state === alien.NORMAL)    {      //Move the current alien if its state is NORMAL      alien.y += alien.vy;    }    //Check if the alien has crossed the bottom of the screen    if(alien.y > canvas.height + alien.height)    {       //End the game if an alien has reached Earth      gameState = OVER;    }  }    //--- The collisions   //Check for a collision between the aliens and missiles  for(var i = 0; i < aliens.length; i++)  {    var alien = aliens[i];    for(var j = 0; j < missiles.length; j++)    {      var missile = missiles[j];      if(hitTestRectangle(missile, alien)      && alien.state === alien.NORMAL)      {        //Destroy the alien        destroyAlien(alien);		scoreNeededToWin--;		        //Update the score        score++;        //Remove the missile        removeObject(missile, missiles);        removeObject(missile, sprites);        //Subtract 1 from the loop counter to compensate        //for the removed missile        j--;      }    }  }    //--- The score   //Display the score  scoreDisplay.text = score;  scoreDisplay02.text = scoreNeededToWin;  //Check for the end of the game  if(score === 60)  {    gameState = OVER;  }}function destroyAlien(alien){  //Change the alien's state and update the object   alien.state = alien.EXPLODED;  alien.update();      //Remove the alien after 1 second  setTimeout(removeAlien, 1000);  //Play the explosion sound  explosionSound.currentTime = 0;  explosionSound.play();    function removeAlien()  {    removeObject(alien, aliens);    removeObject(alien, sprites);  }}function endGame(){  gameOverMessage.visible = true;  if(score < scoreNeededToWin)  {    gameOverMessage.text = "EARTH DESTROYED!";  }  else  {    gameOverMessage.x = 120;    gameOverMessage.text = "EARTH SAVED!";  }}function makeAlien(){  //Create the alien  var alien = Object.create(alienObject);  alien.sourceX = 32;    //Set its y position above the screen boundary  alien.y = 0 - alien.height;    //Assign the alien a random x position  var randomPosition = Math.floor(Math.random() * 15);  //var randomPosition = Math.floor(Math.random() * (canvas.width / alien.width));  alien.x = randomPosition * alien.width;    //Set its speed  alien.vy = 1;    //Push the alien into both the sprites and aliens arrays  sprites.push(alien);  aliens.push(alien);}function fireMissile(){   //Create a missile sprite  var missile = Object.create(spriteObject);  missile.sourceX = 96;  missile.sourceWidth = 16;  missile.sourceHeight = 16;  missile.width = 16;  missile.height = 16;    //Center it over the cannon  missile.x = cannon.centerX() - missile.halfWidth();  missile.y = cannon.y - missile.height;    //Set its speed  missile.vy = -8;    //Push the missile into both the sprites and missiles arrays  sprites.push(missile);  missiles.push(missile);  //Play the firing sound  shootSound.currentTime = 0;  shootSound.play();}function removeObject(objectToRemove, array) {   var i = array.indexOf(objectToRemove);  if (i !== -1)  {    array.splice(i, 1);  }}function endGame(){  gameOverMessage.visible = true;  if(score < scoreNeededToWin)  {    gameOverMessage.text = "EARTH DESTROYED!";  }  else  {    gameOverMessage.x = 120;    gameOverMessage.text = "EARTH SAVED!";  }}function render(){   drawingSurface.clearRect(0, 0, canvas.width, canvas.height);    //Display the sprites  if(sprites.length !== 0)  {    for(var i = 0; i < sprites.length; i++)    {      var sprite = sprites[i];      drawingSurface.drawImage      (        image,         sprite.sourceX, sprite.sourceY,         sprite.sourceWidth, sprite.sourceHeight,        Math.floor(sprite.x), Math.floor(sprite.y),         sprite.width, sprite.height      );     }  }  //Display game messages  if(messages.length !== 0)  {    for(var i = 0; i < messages.length; i++)	{	  var message = messages[i];	  if(message.visible)	  {	    drawingSurface.font = message.font;          drawingSurface.fillStyle = message.fillStyle;        drawingSurface.textBaseline = message.textBaseline;		drawingSurface.fillText(message.text, message.x, message.y);  	  }	}  }}}());
Link to comment
Share on other sites

Where is the code that makes the mouse move the character.

 

By setting the moveLeft and moveRight variables you should be able to move the character regardless of whether the keyboard or mouse changed them.

Link to comment
Share on other sites

cannon.x = Math.max(0, Math.min(cannon.x + cannon.vx, canvas.width - cannon.width));
cannon.x = mouseX - (cannon.halfWidth());

The first is the math that moves the cannon with the keyboard.

The second is the math that moves the cannon with the mouse. (basically cannon.x coordinate is = to

 

Okay, well the issue is that if I set cannon.x = mouseX and the math then the cannon will work with the mouse, but the key board moves it over one increment (8px) then is reset to the mouseX coordinate. So I'm wondering how to make this qwirk with the keyboard handler go away. I got the cannon to work with either one, but I can't make them work at the same time correctly.

Link to comment
Share on other sites

What you need in order to abstract the input from the input device is to have variables that store the value. Both the keyboard and mouse would manipulate the variables.

 

You could rename the mouseX variable in that equation to something more meaningful and have both the mouse handler and the keyboard handler manipulate it. Since I don't have the specifications of your program I don't know exactly what exactly should go there.

Link to comment
Share on other sites

Could you tell me how to write the code to store the info needed to tell a Boolean whether the keyboard or the mouse is in use? I need the cannon.x value to equal a either the keyboard math function or the mouseX coordinate depending which is in use. Thanks for any help. What kind of specifics are needed? Or is their a way to create a prompt button that could handle this?

Edited by thatguy
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...