Home > Net >  Have two sprites appear and move at the same time. One using WASD keys and the other arrow keys. (Ja
Have two sprites appear and move at the same time. One using WASD keys and the other arrow keys. (Ja

Time:09-26

I'm trying to have the sprite "Pounce" move with the arrow keys and the sprite "gsu.G" move witht he arrow keys. Both should be able to appear on the canvas and move at the same time, but for some reason only gsu.G shows up. Could I get some help with this code, I have tried everything. I'm coding in notepad javascript.

<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Simple Animation</title>

<script type="application/javascript">
// <![CDATA[
var INTERVAL = 0;
var DEBUG = false; //true;

var canvas;             // The canvas shown on the page.
var ctx;                // The context, used to access the canvas.

var SpriteRow = 0;      // Row of the graphic to show
var SpriteCol = 0;      // Col of the graphic to show
var MaxSpriteRow = 8;   // How many rows of images
var MaxSpriteCol = 8;  // How many columns of images

var SpriteX = 100;      // Position of sprite on the canvas
var SpriteY = 100;
var SpriteWidth = 32;   // Width, Height of each subimage
var SpriteHeight = 32;

var SpriteImage = new Image();   // Sprite sheet
SpriteImage.src   = "Pounce.png";


// Set up a timer to execute every 50 ms.
var myInterval;


function eraseSprite() {
  // erase sprite
  ctx.clearRect(SpriteX, SpriteY, SpriteWidth, SpriteHeight);
}


function drawSprite() {
  // draw sprite
  //ctx.drawImage(SpriteImage, SpriteX, SpriteY);
  ctx.drawImage(SpriteImage, SpriteCol * SpriteWidth, SpriteRow * SpriteHeight, 
    SpriteWidth, SpriteHeight, SpriteX, SpriteY, SpriteWidth, SpriteHeight); 


  // update the next image to show
  // SpriteCol  ;
  if (SpriteCol >= MaxSpriteCol)
    SpriteCol = 0;
}


function Tick() {

  // Erase the sprite from its current location.
  eraseSprite();

  // Show a new image
  drawSprite();
}


function loadComplete() {
  console.log("Load is complete."); 
  canvas = document.getElementById("theCanvas");
  ctx = canvas.getContext("2d");
  myInterval = self.setInterval(function(){Tick()}, INTERVAL);
}

// What to do when the user presses a key.
function whenKeyPressed(key) {
  switch (key) {
    case 28:  // Right arrow was pressed 
      if(SpriteX < 612){
    eraseSprite();
    SpriteX  ;
    drawSprite();
      }
      break;
    case 29:  // Left arrow, ASCII 29 
      if(SpriteX > 0){
    eraseSprite();
    SpriteX--;
    drawSprite();
      }
      break;
    case 30:  // Up arrow was pressed 
      if(SpriteY > 0){
    eraseSprite();
    SpriteY--;
    drawSprite();
      }
      break;
    case 31:  // Down arrow was pressed
      if(SpriteY < 457) {
    eraseSprite();
    SpriteY  ;
    drawSprite();
      }
      break;
  }
}
///]]>
</script>

</head>
<body onl oad="loadComplete()" bgcolor="#0f0000" text="#ffffff">

<center>
  <canvas id="theCanvas" tabindex="1" width="640" height="480"></canvas>
<h2>Press up/down to see different rows</h2>
</center>

<script type="application/javascript">
  //
  // Set up a function to handle key-presses.
  //
  // This should work across most browsers.
  document['onkeydown'] = function(event) {
    event = event || window.event;
    var key = event.which || event.cursor;
    // Check for a special key value, and map it to ASCII.
    switch (key) {
      case 37:  // Left arrow, ASCII 29 
        key = 29;
        break;
      case 38:  // Up arrow, ASCII 30
        key = 30;
        break;
      case 39:  // Right arrow, ASCII 28  
        key = 28;
        break; 
      case 40:  // Down arrow, ASCII 31
        key = 31;
        break;
    }
    //document.getElementById("keydown").innerHTML =
    //  " key Down event, keycode "   key;
    whenKeyPressed(key);
  };
</script>
<script type="application/javascript">
// <![CDATA[
var INTERVAL = 0;
var DEBUG = false; //true;
var SpriteRow = 0;      // Row of the graphic to show
var SpriteCol = 0;      // Col of the graphic to show
var MaxSpriteRow = 8;   // How many rows of images
var MaxSpriteCol = 8;  // How many columns of images

var SpriteX = 100;      // Position of sprite on the canvas
var SpriteY = 100;
var SpriteWidth = 32;   // Width, Height of each subimage
var SpriteHeight = 32;

var SpriteImage = new Image();   // Sprite sheet
SpriteImage.src   = "Gsug.png";


// Set up a timer to execute every 50 ms.
var myInterval;


function eraseSprite() {
  // erase sprite
  ctx.clearRect(SpriteX, SpriteY, SpriteWidth, SpriteHeight);
}


function drawSprite() {
  // draw sprite
  //ctx.drawImage(SpriteImage, SpriteX, SpriteY);
  ctx.drawImage(SpriteImage, SpriteCol * SpriteWidth, SpriteRow * SpriteHeight, 
    SpriteWidth, SpriteHeight, SpriteX, SpriteY, SpriteWidth, SpriteHeight); 


  // update the next image to show
  // SpriteCol  ;
  if (SpriteCol >= MaxSpriteCol)
    SpriteCol = 0;
}


function Tick() {

  // Erase the sprite from its current location.
  eraseSprite();

  // Show a new image
  drawSprite();
}


function loadComplete() {
  console.log("Load is complete."); 
  canvas = document.getElementById("theCanvas");
  ctx = canvas.getContext("2d");
  myInterval = self.setInterval(function(){Tick()}, INTERVAL);
}

// What to do when the user presses a key.
function whenKeyPressed(key) {
  switch (key) {
    case 68:  // Right arrow was pressed 
      if(SpriteX < 612){
    eraseSprite();
    SpriteX  ;
    drawSprite();
      }
      break;
    case 65:  // Left arrow, ASCII 29 
      if(SpriteX > 0){
    eraseSprite();
    SpriteX--;
    drawSprite();
      }
      break;
    case 87:  // Up arrow was pressed 
      if(SpriteY > 0){
    eraseSprite();
    SpriteY--;
    drawSprite();
      }
      break;
    case 83:  // Down arrow was pressed
      if(SpriteY < 457) {
    eraseSprite();
    SpriteY  ;
    drawSprite();
      }
      break;
  }
}
///]]>
</script>

<script type="application/javascript">
  //
  // Set up a function to handle key-presses.
  //
  // This should work across most browsers.
  document['onkeydown'] = function(event) {
    event = event || window.event;
   var key = event.which || event.cursor;
    // Check for a special key value, and map it to ASCII.
    switch (key) {
      case 119:  // Left arrow, ASCII 29 
        key = 87;
        break;
      case 115:  // Up arrow, ASCII 30
        key = 83;
        break;
      case 100:  // Right arrow, ASCII 28  
        key = 67;
        break; 
      case  97:  // Down arrow, ASCII 31
        key =68;
        break;
    }
    //document.getElementById("keydown").innerHTML =
    //  " key Down event, keycode "   key;
    whenKeyPressed(key);
  };
</script>


</body></html>

CodePudding user response:

Your function whenKeyPressed is defined twice. As well as almost every other function on the page.

When the second instance of the function is parsed, your original version vanishes into thin air.

That’s why only one of them show up.

You’ll need to work on making one instance of the function work in both cases.

In the case of whenKeyPressed, just combine all of the cases in your switch statements into one switch statement and delete the second instance of the function.

You’ll need to do the same for the others.

CodePudding user response:

The following is a rough guide and not tested at all, but will hopefully get you on the right path.

Your code at moment won't work as you are effectiveloy overwriting method and variables.

Here I've created a master object using JSON : sprites which contains an object for each sprites and maintains their states. The key mappings are associate with each sprite and can be expanded by adding to the DirectionKeyCodes propety on each of the sprite objects.

The active sprite is determined based on key press and is then passes to each of the worker functions.

var INTERVAL = 0;
var DEBUG = false; //true;

var canvas; // The canvas shown on the page.
var ctx; // The context, used to access the canvas.

let baseValues = {
  "SpriteRow": 0, // Row of the graphic to show
  "SpriteCol": 0, // Col of the graphic to show
  "MaxSpriteRow": 8, // How many rows of images
  "MaxSpriteCol": 8, // How many columns of images

  "SpriteX": 100, // Position of sprite on the canvas
  "SpriteY": 100,
  "SpriteWidth": 32; // Width, Height of each subimage
  "SpriteHeight": 32;
};

let pounceSprite = new Image();
pounceSprite.src = "Pounce.png";
let gsugSprite = new Image();
gsugSprite.src = "Gsug.png";

let sprites = {
    "Pounce": {
      "SpriteRow": baseValues.SpriteRow,
      "SpriteCol": baseValues.SpriteCol, // Col of the graphic to show
      "MaxSpriteRow": baseValues.MaxSpriteRow,
      "MaxSpriteCol": baseValues.MaxSpriteCol, // How many columns of images

      "SpriteX": baseValues.SpriteX, // Position of sprite on the canvas
      "SpriteY": baseValues.SpriteY,
      "SpriteWidth": baseValues.SpriteWidth, // Width, Height of each subimage
      "SpriteHeight": baseValues.SpriteHeight,
      "DirectionKeyCodes": {
        "87": "UP",
        "83": "DOWN",
        "65": "LEFT",
        "70": "RIGHT"
      },
      "Sprite": pounceSprite
    }
  },
  "Gsug": {
    "SpriteRow": baseValues.SpriteRow,
    "SpriteCol": baseValues.SpriteCol, // Col of the graphic to show
    "MaxSpriteRow": baseValues.MaxSpriteRow,
    "MaxSpriteCol": baseValues.MaxSpriteCol, // How many columns of images

    "SpriteX": baseValues.SpriteX, // Position of sprite on the canvas
    "SpriteY": baseValues.SpriteY,
    "SpriteWidth": baseValues.SpriteWidth, // Width, Height of each subimage
    "SpriteHeight": baseValues.SpriteHeight,
    "DirectionKeyCodes": {
      "38": "UP",
      "40": "DOWN",
      "37": "LEFT",
      "39": "RIGHT"
    },
    "Sprite": gsugSprite
  }
}

// Set up a timer to execute every 50 ms.
var myInterval;

function eraseSprite(sprite) {
  // erase sprite
  ctx.clearRect(sprite.SpriteX, sprite.SpriteY, sprite.SpriteWidth, sprite.SpriteHeight);
}

function drawSprite(sprite) {
  // draw sprite
  //ctx.drawImage(SpriteImage, SpriteX, SpriteY);
  ctx.drawImage(sprite.SpriteImage, sprite.SpriteCol * sprite.SpriteWidth, sprite.SpriteRow * sprite.SpriteHeight,
    sprite.SpriteWidth, sprite.SpriteHeight, sprite.SpriteX, sprite.SpriteY, sprite.SpriteWidth, sprite.SpriteHeight);


  // update the next image to show
  // SpriteCol  ;
  if (sprite.SpriteCol >= sprite.MaxSpriteCol)
    sprite.SpriteCol = 0;
}

function Tick() {
  for (const sprite in sprites) {
    // Erase the sprite from its current location.
    eraseSprite(sprite);
    // Show a new image
    drawSprite(sprite);
  }
}


function loadComplete() {
  console.log("Load is complete.");
  canvas = document.getElementById("theCanvas");
  ctx = canvas.getContext("2d");
  myInterval = self.setInterval(function() {
    Tick()
  }, INTERVAL);
}

// What to do when the user presses a key.
function whenKeyPressed(keyCode, sprite) {
  switch (sprite.DirectionKeyCodes[keyCode]) {
    case "RIGHT": 
      if (sprite.SpriteX < 612) {
        eraseSprite(sprite);
        sprite.SpriteX  ;
        drawSprite(sprite);
      }
      break;
    case "LEFT": 
      if (sprite.SpriteX > 0) {
        eraseSprite(sprite);
        sprite.SpriteX--;
        drawSprite(sprite);
      }
      break;
    case "UP": 
      if (sprite.SpriteY > 0) {
        eraseSprite(sprite);
        sprite.SpriteY--;
        drawSprite(sprite);
      }
      break;
    case "DOWN": 
      if (sprite.SpriteY < 457) {
        eraseSprite(sprite);
        sprite.SpriteY  ;
        drawSprite(sprite);
      }
      break;
  }
}
//
// Set up a function to handle key-presses.
//
// This should work across most browsers.
document['onkeydown'] = function(event) {
  event = event || window.event;
  var key = event.which || event.cursor;
  //Work out what sprite we need
  let sprite = null;
  //Itteate the sprites in our object
  for (const spriteTemp in sprites) {
    //If it has a key mapping that matches the key press, we have our sprite
    if (spriteTemp.DirectionKeyCodes.hasOwnProperty(key)) {
      sprite = spriteTemp;
      break;
    }
  }

  //If we found a sprite
  if (sprite !== null) {
    //Send the key and sprite to the work method
    whenKeyPressed(key, sprite);
  }
}

  • Related