Tile map collide not working as expected in Javascript - javascript
I have been thinking of a way to set-up tile map collision with a player in the same way I have developed the game so far (or similar way if possible, so I do not have to redo everything :) ).
I got some ideas from tutorials and videos and decided to implement it to my code and the player definitely collides with something, though it doesn't look to be the correct tiles that it should be.
For example I want it to walk on over the tiles with Index 1, but to collide with tiles with Index 0 and 3, to stop the player movement.
Here is what I got so far:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas Tile Map</title>
<style>
#canvas{
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" height="650px" width="1000px"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var go = 0;
var canvasBegX = -64;
var canvasEndX = 999;
var canvasBegY = -64;
var canvasEndY = 649;
var heroX = 0;
var heroY = 0;
var heroIndexX = 0;
var heroIndexY = 0;
var heroIndexXnew = 0;
var heroIndexYnew = 0;
//--------------------------------------------------------------
//ADD CHECKER IF KEY IS PRESSED OR RELEASED
window.addEventListener('keydown', function (e) {
canvas.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
canvas.key = false;
})
//--------------------------------------------------------------
//THE MAP
var mapArray=[
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,3],
[3,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,3],
[3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,3],
[3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,3],
[3,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,3],
[3,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3],
[3,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,3],
[3,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,3],
[3,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,1,1,0,0,3],
[3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
];
// x= 22
// y= 15
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
// DRAW PLAYER
player_image = new Image();
var player = new Object();
player.y = canvas.height/2-220; //player position y
player.x = canvas.width/2-340; //player position x
player.Width = 60;
player.Height = 60;
function drawPlayer() { // drawing the player
context.beginPath();
context.fillStyle = "red";
context.fillRect(player.x,player.y,player.Width,player.Height);
context.closePath();
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
// These I need for the map co-ordinates and when it moves the map upon key-press
var updateX=(player.x-210); // Starting point of canvas X
var updateY=(player.y-160); // Starting point of canvas Y
var posX=updateX;
var posY=updateY;
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//DRAW THE MAP AND THE PLAYER
var grass = new Image();
var stone = new Image();
var black = new Image();
function drawMap() {
var posY = updateY; // new Y coordinates for the map after movement
grass.src= 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/grass.jpeg';
stone.src = 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/sand.jpeg';
black.src = 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/black.png';
//---------------------------------------------------------
// Draw the map loop
grass.onload = function (){
stone.onload = function (){
black.onload = function (){
for(var i=0; i < mapArray.length; i++){
for(var j=0; j < mapArray[i].length; j++){
if(mapArray[i][j]==0){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(grass,posX, posY, 64, 64); // Load image for grass "0"
}
}
if(mapArray[i][j]==1){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(stone,posX,posY,64,64); // Load image for stone "1"
}
}
if(mapArray[i][j]==3){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(black,posX,posY,64,64); // Load image for black "3"
}
}
posX+=64;
}
posY+=64;
posX=updateX; // new X coordinates for the map after movement
//---------------------------------------------------------
drawPlayer(); // Draw the player
}
}
}
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// PLAYER MOVEMENT BUTTONS
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
var endX=1408;
var endY=960;
document.addEventListener("keydown", keyDownHandler);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
if(e.keyCode == 40) {
downPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
}
document.addEventListener("keyup", keyUpHandler);
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
if(e.keyCode == 40) {
downPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
}
//----------------------------------------------
//THE ACTUAL MOVEMENT + BOUNDARIES
function playerMovement(){
//------------------------------
//CHECK PLAYER X AND Y IN TILE INDEXES
heroX = Math.abs(updateX - player.x); //current hero X position starting from beginning of tilemap(outside of visible part)
heroY = Math.abs(updateY - player.y); //current hero Y position starting from beginning of tilemap(outside of visible part)
heroIndexX = heroX/64; // X index of hero to chech in which tile is currently located
heroIndexY = heroY/64; // Y index of hero to chech in which tile is currently located
heroIndexXnew = Math.ceil(heroIndexX); //index positioned on the right of the heroes index
heroIndexYnew = Math.ceil(heroIndexY) -2; //index positioned on the left of the heroes index
if(rightPressed) {
if (isPathTile(mapArray, heroIndexXnew, heroIndexYnew)){ // Nothing happens because you hit a tile
}else {
moveRight(); // if you are not at the wall, you go right
}
}
//------------------------------
else if(leftPressed) {
if (isPathTile(mapArray, heroIndexXnew - 2, heroIndexYnew)){ // Nothing happens because you hit a tile
}else {
moveLeft(); // if you are not at the wall, you go left
}
}
//------------------------------
if(downPressed) {
if(player.y>updateY+834){} // Nothing happens because you hit the bottom wall
else {
moveDown(); // if you are not at the wall, you go down
}
}
//------------------------------
else if(upPressed) {
if(player.y<updateY+64){} // Nothing happens because you hit the top wall
else {
moveUp(); // if you are not at the wall, you go up
}
}
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//CAMERA BOUNDARIES
function moveRight(){
if(player.x<820){
player.x=player.x+4.1; //If you are at this position, move the player
}
else if(player.x>820){
updateX=updateX-4.1; //If you go over this position, move the background
}
}
function moveLeft(){
if(player.x>100){
player.x=player.x-4.1; //If you are at this position, move the player
}
else if(player.x<100){
updateX=updateX+4.1; //If you go over this position, move the background
}
}
function moveUp(){
if(player.y>80){
player.y=player.y-4.1; //If you are at this position, move the player
}
else if(player.y<80){
updateY=updateY+4.1; //If you go over this position, move the background
}
}
function moveDown(){
if(player.y<500){
player.y=player.y+4.1; //If you are at this position, move the player
}
else if(player.y>500){
updateY=updateY-4.1; //If you go over this position, move the background
}
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// MOVEMENT BOUNDARIES WITH TILES
function isPathTile(mapArray, x, y) {
return (mapArray[x][y] === 0); // Because 0 is the path tile
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// THE GAME LOOP
function gameLoop(){
console.log("index X =" + heroIndexXnew);
console.log("index Y =" + heroIndexYnew);
playerMovement(); //Check for movements
drawMap(); //Draw the map and the player
requestAnimationFrame(gameLoop);
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
gameLoop(); // start the gameLoop
</script>
</body>
</html>
And here is a code to test it -
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var go = 0;
var canvasBegX = -64;
var canvasEndX = 999;
var canvasBegY = -64;
var canvasEndY = 649;
var heroX = 0;
var heroY = 0;
var heroIndexX = 0;
var heroIndexY = 0;
var heroIndexXnew = 0;
var heroIndexYnew = 0;
//--------------------------------------------------------------
//ADD CHECKER IF KEY IS PRESSED OR RELEASED
window.addEventListener('keydown', function (e) {
canvas.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
canvas.key = false;
})
//--------------------------------------------------------------
//THE MAP
var mapArray=[
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3],
[3,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,3],
[3,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,3],
[3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,3],
[3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,3],
[3,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,3],
[3,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,3],
[3,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3],
[3,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,3],
[3,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,1,3],
[3,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,1,1,0,0,3],
[3,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,3],
[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]
];
// x= 22
// y= 15
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
// DRAW PLAYER
player_image = new Image();
var player = new Object();
player.y = canvas.height/2-220; //player position y
player.x = canvas.width/2-340; //player position x
player.Width = 60;
player.Height = 60;
function drawPlayer() { // drawing the player
context.beginPath();
context.fillStyle = "red";
context.fillRect(player.x,player.y,player.Width,player.Height);
context.closePath();
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
// These I need for the map co-ordinates and when it moves the map upon key-press
var updateX=(player.x-210); // Starting point of canvas X
var updateY=(player.y-160); // Starting point of canvas Y
var posX=updateX;
var posY=updateY;
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
//DRAW THE MAP AND THE PLAYER
var grass = new Image();
var stone = new Image();
var black = new Image();
function drawMap() {
var posY = updateY; // new Y coordinates for the map after movement
grass.src= 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/grass.jpeg';
stone.src = 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/sand.jpeg';
black.src = 'https://sarahkerrigan.biz/wpmtest/hosting/images/tile/black.png';
//---------------------------------------------------------
// Draw the map loop
grass.onload = function (){
stone.onload = function (){
black.onload = function (){
for(var i=0; i < mapArray.length; i++){
for(var j=0; j < mapArray[i].length; j++){
if(mapArray[i][j]==0){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(grass,posX, posY, 64, 64); // Load image for grass "0"
}
}
if(mapArray[i][j]==1){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(stone,posX,posY,64,64); // Load image for stone "1"
}
}
if(mapArray[i][j]==3){
if (posY > canvasBegY && posY < canvasEndY && posX > canvasBegX && posX < canvasEndX){
context.drawImage(black,posX,posY,64,64); // Load image for black "3"
}
}
posX+=64;
}
posY+=64;
posX=updateX; // new X coordinates for the map after movement
//---------------------------------------------------------
drawPlayer(); // Draw the player
}
}
}
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// PLAYER MOVEMENT BUTTONS
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
var endX=1408;
var endY=960;
document.addEventListener("keydown", keyDownHandler);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
if(e.keyCode == 40) {
downPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
}
document.addEventListener("keyup", keyUpHandler);
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
if(e.keyCode == 40) {
downPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
}
//----------------------------------------------
//THE ACTUAL MOVEMENT + BOUNDARIES
function playerMovement(){
//------------------------------
//CHECK PLAYER X AND Y IN TILE INDEXES
heroX = Math.abs(updateX - player.x); //current hero X position starting from beginning of tilemap(outside of visible part)
heroY = Math.abs(updateY - player.y); //current hero Y position starting from beginning of tilemap(outside of visible part)
heroIndexX = heroX/64; // X index of hero to chech in which tile is currently located
heroIndexY = heroY/64; // Y index of hero to chech in which tile is currently located
heroIndexXnew = Math.ceil(heroIndexX); //index positioned on the right of the heroes index
heroIndexYnew = Math.ceil(heroIndexY) -2; //index positioned on the left of the heroes index
if(rightPressed) {
if (isPathTile(mapArray, heroIndexXnew, heroIndexYnew)){ // Nothing happens because you hit a tile
}else {
moveRight(); // if you are not at the wall, you go right
}
}
//------------------------------
else if(leftPressed) {
if (isPathTile(mapArray, heroIndexXnew - 2, heroIndexYnew)){ // Nothing happens because you hit a tile
}else {
moveLeft(); // if you are not at the wall, you go left
}
}
//------------------------------
if(downPressed) {
if(player.y>updateY+834){} // Nothing happens because you hit the bottom wall
else {
moveDown(); // if you are not at the wall, you go down
}
}
//------------------------------
else if(upPressed) {
if(player.y<updateY+64){} // Nothing happens because you hit the top wall
else {
moveUp(); // if you are not at the wall, you go up
}
}
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//CAMERA BOUNDARIES
function moveRight(){
if(player.x<820){
player.x=player.x+4.1; //If you are at this position, move the player
}
else if(player.x>820){
updateX=updateX-4.1; //If you go over this position, move the background
}
}
function moveLeft(){
if(player.x>100){
player.x=player.x-4.1; //If you are at this position, move the player
}
else if(player.x<100){
updateX=updateX+4.1; //If you go over this position, move the background
}
}
function moveUp(){
if(player.y>80){
player.y=player.y-4.1; //If you are at this position, move the player
}
else if(player.y<80){
updateY=updateY+4.1; //If you go over this position, move the background
}
}
function moveDown(){
if(player.y<500){
player.y=player.y+4.1; //If you are at this position, move the player
}
else if(player.y>500){
updateY=updateY-4.1; //If you go over this position, move the background
}
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// MOVEMENT BOUNDARIES WITH TILES
function isPathTile(mapArray, x, y) {
return (mapArray[x][y] === 0); // Because 0 is the path tile
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
// THE GAME LOOP
function gameLoop(){
console.log("index X =" + heroIndexXnew);
console.log("index Y =" + heroIndexYnew);
playerMovement(); //Check for movements
drawMap(); //Draw the map and the player
requestAnimationFrame(gameLoop);
}
//-----------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------
gameLoop(); // start the gameLoop
#canvas{
border: 1px solid black;
}
<canvas id="canvas" height="650px" width="1000px"></canvas>
All the code has some vars, the tilemap array, drawing the tilemap in only the visible part of the canvas , the player of course with it for every time it draws, then we have the movement and where I believe something is not set correctly. There is a function isPathTile to see if the index next to the current player location is 0 and if it is, it does nothing (when right pressed, so the player does not move). I think that this is where I got it wrong. Much appreciated if anyone can take can a look at this.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// IIFE
// https://developer.mozilla.org/en-US/docs/Glossary/IIFE
void function() {
// Enforce strict mode inside the IIFE
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
"use strict";
// Var declaration
var canvasWidth = 320;
var canvasHeight = 320;
var canvas = null;
var ctx = null;
var player = {
// Position
x: 35.0,
y: 35.0,
// Velocity
dx: 0.0,
dy: 0.0,
// Size
width: 20,
height: 20,
// Input
up: false,
down: false,
left: false,
right: false
};
// Defined this way the map will need to be indexed as
// map[y][x]
// 0 = not solid
// 1 = solid
var mapTileSize = 32; // size for each tile in pixels
var map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,1,0,0,0,0,0,1,1],
[1,0,0,1,1,1,0,1,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,0,0,0,0,0,1,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1]
];
// Runs after the page has finished loading
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
loop();
}
// Key Input
window.onkeydown = function(e) {
switch(e.key) {
case "w": player.up = true; break;
case "s": player.down = true; break;
case "a": player.left = true; break;
case "d": player.right = true; break;
}
}
window.onkeyup = function(e) {
switch(e.key) {
case "w": player.up = false; break;
case "s": player.down = false; break;
case "a": player.left = false; break;
case "d": player.right = false; break;
}
}
function loop() {
// Tick
// Player movement
if (player.up) {
player.dy = -2;
}
if (player.down) {
player.dy = +2;
}
if (!player.up && !player.down) {
player.dy = 0;
}
if (player.left) {
player.dx = -2;
}
if (player.right) {
player.dx = +2;
}
if (!player.left && !player.right) {
player.dx = 0;
}
// Collision detection & resolution
// Only perform collision detection in either axis
// if the player is actually moving on that axis
// Map grid coordinates at the corners of the player's bounding box
/*
-> *-----* <-
| |
| |
| |
-> *-----* <-
*/
var invMapTileSize = 1.0 / mapTileSize;
var nextX = player.x + player.dx;
var nextY = player.y + player.dy;
// Current position
var currentMinX = (player.x * invMapTileSize) | 0;
var currentMaxX = ((player.x + player.width) * invMapTileSize) | 0;
var currentMinY = (player.y * invMapTileSize) | 0;
var currentMaxY = ((player.y + player.height) * invMapTileSize) | 0;
// Next position
var nextMinX = (nextX * invMapTileSize) | 0;
var nextMaxX = ((nextX + player.width) * invMapTileSize) | 0;
var nextMinY = (nextY * invMapTileSize) | 0;
var nextMaxY = ((nextY + player.height) * invMapTileSize) | 0;
/*
Collision checks are performed down along each axis of the player's
collision box, this way it won't matter if the player is larger
or smaller then the map tiles.
*/
// X axis collision
if (player.dx !== 0.0) {
for (var x = nextMinX; x <= nextMaxX; ++x) {
for (var y = currentMinY; y <= currentMaxY; ++y) {
if (map[y][x]) {
player.dx = 0.0;
break;
}
}
}
}
// Y axis collision
if (player.dy !== 0.0) {
for (var y = nextMinY; y <= nextMaxY; ++y) {
for (var x = currentMinX; x <= currentMaxX; ++x) {
if (map[y][x]) {
player.dy = 0.0;
break;
}
}
}
}
// Update player position
player.x = player.x + player.dx;
player.y = player.y + player.dy;
// render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
// draw map
ctx.fillStyle = "darkred";
ctx.beginPath();
for (var y = 0; y < map.length; ++y) {
for (var x = 0; x < map[0].length; ++x) {
if (map[y][x]) {
ctx.rect(
x * mapTileSize,
y * mapTileSize,
mapTileSize,
mapTileSize
);
}
}
}
ctx.fill();
// draw player
ctx.fillStyle = "darkblue";
ctx.fillRect(
player.x,
player.y,
player.width,
player.height
);
//
requestAnimationFrame(loop);
}
}();
</script>
</body>
</html>
After about a week was giving up on this one :D and finally figured it out. I was switching the places of my X and Y indexes and that is why it was not acting as it should be. Showing up the fix here if anyone is interested (only the Player movement has to be updated):
function playerMovement(){
//------------------------------
//CHECK PLAYER X AND Y IN TILE INDEXES
heroX = -updateX + player.x;
heroY = -updateY + player.y;
heroIndexX = heroX/64; // get the X index
heroIndexY = heroY/64; // get the Y index
heroIndexXnew = Math.ceil(heroIndexX);
heroIndexYnew = Math.ceil(heroIndexY);
if(rightPressed) {
player_image.src = './images/horseright1.png';
if(player.x>updateX+1258){ // Nothing happens because you hit the right wall
}else if (isPathTile(mapArray, heroIndexYnew, heroIndexXnew)){ // Nothing happens because you hit a tile
}else {
moveRight(); // if you are not at the wall, you go right
}
}
//------------------------------
else if(leftPressed) {
player_image.src = './images/horseleft1.png';
if(player.x<updateX+128){ // Nothing happens because you hit the left wall
}else if (isPathTile(mapArray, heroIndexYnew, heroIndexXnew - 1)){ // Nothing happens because you hit a tile
}else {
moveLeft(); // if you are not at the wall, you go left
}
}
//------------------------------
if(downPressed) {
if(player.y>updateY+834){ // Nothing happens because you hit the bottom wall
}else if (isPathTile(mapArray, heroIndexYnew, heroIndexXnew)){ // Nothing happens because you hit a tile
}else {
moveDown(); // if you are not at the wall, you go down
}
}
//------------------------------
else if(upPressed) {
if(player.y<updateY+64){ // Nothing happens because you hit the top wall
}else if (isPathTile(mapArray, heroIndexYnew - 1, heroIndexXnew)){ // Nothing happens because you hit a tile
}else {
moveUp(); // if you are not at the wall, you go up
}
}
}
A simple mistake and took me one hell of a time for debugging, though the logic is good and simple. Needs a bit of a touch on how it collides exactly as there are few things to be updated, but overall it works great!
Related
Javascript snake game bugs
There are two issues, I can't control the snake, and now it just resets constantly without giving the snake a chance to move. I figured that if i kept coding the problem would go away but sadly its not a perfect world. I tried different key codes for controlling the snake but it didn't work. window.onload = function() { var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); var cvsW = cvs.width; var cvsH = cvs.height; var snekW = 10; var snekH = 10; //score var score = 0; //default direction var direction = "right"; //read users directions document.addEventListener("keydown",getDirection); //To my knowledge this function should control the snake with the keyboard function getDirection(e) { if(e.keyCode == 37 && direction != "right"){ direction = "left"; }else if(e.keyCode == 38 && direction != "down"){ direction = "up"; }else if(e.keyCode == 39 && direction != "left"){ direction = "right"; }else if(e.keycode == 40 && direction != "up"){ direction = "down"; } } function drawSnek(x,y) { ctx.fillStyle = "Lime"; ctx.fillRect(x*snekW,y*snekH,snekW,snekH); ctx.fillStyle = "#000"; ctx.strokeRect(x*snekW,y*snekH,snekW,snekH); } var len = 4; //default length of the snake var snek = []; //the snake is an array for(var i = len-1; i>=0; i--) { snek.push({x:i,y:0}); } //exceptions for direction of snake if(direction == "left") snekx--; else if( direction == "up") sneky--; else if( direction == "right") snekx++; else if( direction == "down") sneky++; //Functions for creating snake food have been removed. var newHead = { x: snekx, y: sneky}; snek.unshift(newHead); drawScore(score); } setInterval(draw, 10); //I do not fully understand this function }
There were several issues with your code: You needed a draw function that could be called in an interval. In this draw function you could draw the individual parts of the snake. You were unable to control the snake correctly as you had a typo in the down part of the callback function. You have to either introduce x / y variables for the head of the snake or use the first element of the array to retrieve it. Unshifting the new position using snek.unshift will cause the snake to grow indefinitely. Removing array elements using snek.splice(len,snek.length - len); solves this problem. If you only draw new elements to the screen the old parts you drew will still exist in new frames. A good idea would be to clear the canvas using ctx.clearRect(0, 0, cvsW, cvsH); window.onload = function () { var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); var cvsW = cvs.width; var cvsH = cvs.height; var snekW = 10; var snekH = 10; //score var score = 0; //default direction var direction = "right"; //read users directions document.addEventListener("keydown", getDirection); //To my knowledge this function should control the snake with the keyboard function getDirection(e) { if (e.keyCode == 37 && direction != "right") { direction = "left"; } else if (e.keyCode == 38 && direction != "down") { direction = "up"; } else if (e.keyCode == 39 && direction != "left") { direction = "right"; } else if (e.keyCode == 40 && direction != "up") { direction = "down"; } } function drawSnek(x, y) { ctx.fillStyle = "Lime"; ctx.fillRect(x * snekW, y * snekH, snekW, snekH); ctx.fillStyle = "#000"; ctx.strokeRect(x * snekW, y * snekH, snekW, snekH); } let snekx = 0; let sneky = 0; var len = 4; //default length of the snake var snek = []; //the snake is an array for (var i = len - 1; i >= 0; i--) { snek.push({ x: i, y: 0 }); } function draw() { ctx.clearRect(0, 0, cvsW, cvsH); //exceptions for direction of snake if (direction == "left") snekx--; else if (direction == "up") sneky--; else if (direction == "right") snekx++; else if (direction == "down") sneky++; //Functions for creating snake food have been removed. var newHead = { x: snekx, y: sneky }; snek.unshift(newHead); for(let i = 0; i < snek.length; i++) { drawSnek(snek[i].x, snek[i].y) } snek.splice(len,snek.length - len); //drawScore(score); } setInterval(draw, 50); //I do not fully understand this function } CodePen with fixed code: https://codepen.io/lukasmoeller/pen/PvVzqq?editors=1111 (boundaries are not checked - the snake will leave the canvas) Explanation of setInterval(fn, interval) setInterval calls the function specified using fn every interval ms until it is cleared. The interval can be cleared by using clearInterval, passing it the return value of setInterval. If you want to delay function execution at the beginning you could add setTimeout, add a callback that sets the interval: setTimeout(function(){ setInterval(draw, 50); }, 1000) This would only start drawing the game every 50 ms after 1000ms have passed.
Cannot get player to move in 2D Platformer
I'm trying to create a 2D platformer in JavaScript, I'm getting no errors, but it's not working properly. Pressing the left arrow or the up arrow key does nothing, pressing the right arrow key causes the X-Pos to start incrementing by 1 pixel per tick. I realize this code is long and my 'physics' logic is completely twisted and backwards, but I can't understand anyone's guides on how to add phsyics and velocity and acceleration and gravity and I'm just super confused. I started using JavaScript a week ago and I really have no idea what I'm doing, so any recommendations about any of my code, even things that aren't technically 'problems' would be most appreciated. Thanks guys, you're dope <3 <!DOCTYPE html> <html> <meta charset="utf-8"/> <head> <title>For The Intended</title> </head> <body> <canvas id="canvas" width="1200" height="800"></canvas> <!-- <script src="platform.js"></script> --> <script> // //notes // //Block collision should come when velocity tries to move, and the x-y position should be player.x + player.velocity to check exactly where the collision will be // // // // // // //Canvas Settings var cvs = document.getElementById("canvas"); var ctx = cvs.getContext('2d'); cvs.style = "position:absolute; left: 60%; width: 1200; margin-left: -800px"; //Variables var platforms = []; var imgCount = 0 var totalImgCount = 3 var lastUpdate = Date.now(); var keys = {}; //Controls //Images var platformImage = new Image(); var playerImage = new Image(); var bgImage = new Image(); platformImage.src = "images/platform.png"; playerImage.src = "images/forward1.png"; playerImage.src = "images/backward1.png"; bgImage.src = "images/bg.png"; platformImage.onload = function() { imgCount += 1 } playerImage.onload = function() { imgCount += 1 } bgImage.onload = function() { imgCount += 1 } //Objects //Platforms function Platform(x, y, length, height) { this.x = x; this.y = y; this.length = length; this.height = height; platforms.push(this) } platform = new Platform(30,30,30,30) platform = new Platform(40,40,40,40) //Player function Player(x, y, gravity, velocityX, velocityY, acceleration, isJumping, direction){ this.x = x this.y = y this.gravity = gravity this.velocityX = velocityX this.velocityY = velocityY this.acceleration = acceleration this.isJumping = isJumping this.direction = direction } player = new Player(200, 600, 0.7, 1, 1, false, "forward") function jump() { if (player.isJumping == false) { player.velocityY = -15; player.isJumping = true; } } function jumpingHandler() { if (player.isJumping) { player.velocityY += player.gravity; player.y += player.velocityY; draw(); if (player.y > 600) { player.y = 600; player.velocityY = 0; player.isJumping = false; } } } *function move(e) { if(keys[e.keyCode]) { if(keys[38]) { jump(); } if(keys[37]) { if (player.x > 150){ if (player.acceleration > -5){ player.acceleration = Math.floor(player.acceleration); player.acceleratoion -= 1 player.acceleration = Math.floor(player.acceleration); } player.direction = "backward" playerImage.src = "images/backward1.png"; } } if(keys[39]) { if (player.x < 1050){ console.log("hey") if (player.acceleration < 5){ console.log("hey2") player.acceleration = Math.floor(player.acceleration); player.acceleration += 1 player.acceleration = Math.floor(player.acceleration); } player.direction = "forward" playerImage.src = "images/forward1.png"; } } } }* //Game Requirements function draw() { if (imgCount == 3) { for (var i = 0; i < platforms.length; i++) { ctx.drawImage(platformImage, platforms[i].x, platforms[i].y) //Do something } ctx.drawImage(playerImage, player.x, player.y) } } setInterval(update, 33); function updateKeys() { window.onkeyup = function(e) { keys[e.keyCode] = false; move(e)} window.onkeydown = function(e) { keys[e.keyCode] = true; move(e)} } function update() { if (player.acceleration > 1) {player.acceleration -= 0.2} if (player.acceleration < 1) {player.acceleration += 0.2} player.acceleration = Math.floor(player.acceleration); player.velocityX = player.acceleration player.x += (player.velocityX) console.log("Velocity" + player.velocityX) console.log("Acceleration" + player.acceleration) console.log("X-Pos" + player.x) jumpingHandler() updateKeys() draw() } </script> </body> </html>
object moves through keyboard arrow keys using html5 and javascript
how can i move the object with keyboard keys using html5 and javascript. Here i tried it with below code but it is not moving can any one help to move the object using keyboard arrow keys? <!DOCTYPE html> <html> <head> </head> <body onLoad="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='green'> <canvas id="mycanvas"></canvas> <script> var canvas = document.getElementById('mycanvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(100, 100, 50, 0.25 * Math.PI, 1.25 * Math.PI, false); ctx.fillStyle = "rgb(255, 255, 0)"; ctx.fill(); ctx.beginPath(); ctx.arc(100, 100, 50, 0.75 * Math.PI, 1.75 * Math.PI, false); ctx.fill(); ctx.beginPath(); ctx.arc(100, 75, 10, 0, 2 * Math.PI, false); ctx.fillStyle = "rgb(0, 0, 0)"; ctx.fill(); //moves// var xpos=500; var ypos=550; var xspeed=1; var yspeed=0; var maxspeed=5; //boundaries// var minx=500; var miny=200; var maxx=990; var maxy=400; //controller var upPressed=0; var downPressed=1; var leftPressed=0; var rightPressed=0; function slowDownX() { if(xspeed > 0) xspeed=xspeed-1; if(xspeed<0) xspeed=xspeed+1; } function slowDownY() { if(yspeed > 0) yspeed = yspeed-1; if(yspeed < 0) yspeed = yspeed+1; } function gameLoop() { xpos=Math.min(Math.max(xpos+xspeed,minx),maxx); ypos=Math.min(Math.max(ypos+yspeed,miny),maxy); xpos = document.getElementById('mycanvas').style.left; ypos = document.getElementById('mycanvas').style.top; if (upPressed == 1) yspeed = Math.max(yspeed - 3,-3*maxSpeed); if (downPressed == 1) yspeed = Math.min(yspeed + 3,3*maxSpeed) if (rightPressed == 1) xspeed = Math.min(xspeed + 1,1*maxSpeed); if (leftPressed == 1) xspeed = Math.max(xspeed - 1,-1*maxSpeed); if (upPressed == 0 && downPressed == 0) slowDownY(); if (leftPressed == 0 && rightPressed == 0) slowDownX(); return setTimeout("gameLoop()",10); } function keyDown(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 1; if (code == 40) downPressed = 1; if (code == 37) leftPressed = 1; if (code == 39) rightPressed = 1; } function keyUp(e) { var code = e.keyCode ? e.keyCode : e.which; if (code == 38) upPressed = 0; if (code == 40) downPressed = 0; if (code == 37) leftPressed = 0; if (code == 39) rightPressed = 0; } </script> </body> </html>
Here are the basics of drawing a shape on the html canvas and moving it with arrowkeys Disclaimer: this code is not best game technique, it’s meant for clear instruction. ;) First create a few variables that define a ball: // the ball will be at coordinates 70,75 var ballX=70; var ballY=75; // the ball will have a radius of 15; var ballRadius=15; Next create a function that will draw that ball at the specified coordinates function draw(){ // clear the canvas for the next frame ctx.clearRect(0,0,canvas.width,canvas.height); // draw a ball that the use can move with left/right arrow keys // the ball's center will be at BallX / BallY // the ball will have a radius of BallRadius ctx.beginPath(); ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false); ctx.closePath(); ctx.fill(); } Now listen for user’s keystrokes. // Listen for when the user presses a key down window.addEventListener("keydown", keyDownHandler, true); When the user presses a key down: If the user presses the left or right arrows, move the ball by changing it’s “ballX” coordinate. After changing the balls position, redraw the canvas This code handles when a key is down (called by the addEventListener): // Here we just handle command keys function keyDownHandler(event){ // get which key the user pressed var key=event.which; // Let keypress handle displayable characters if(key>46){ return; } switch(key){ case 37: // left key // move the ball 1 left by subtracting 1 from ballX ballX -= 1; break; case 39: // right key // move the ball 1 right by adding 1 to ballX ballX += 1; break; default: break; } // redraw the ball in its new position draw(); } Here is code and a Fiddle: http://jsfiddle.net/m1erickson/TsXmx/ <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> body{ background-color: ivory; padding:20px;} #canvas{border:1px solid red;} </style> <script> $(function(){ var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); ctx.strokeStyle="blue"; ctx.fillStyle="red"; var ballX=70; var ballY=75; var ballRadius=15; var leftWall=30; var rightWall=120; draw(); function draw(){ // clear the canvas for the next frame ctx.clearRect(0,0,canvas.width,canvas.height); // tell canvas to start a new path // draw walls on left and right ctx.beginPath(); ctx.moveTo(leftWall,0); ctx.lineTo(leftWall,canvas.height); ctx.moveTo(rightWall,0); ctx.lineTo(rightWall,canvas.height); ctx.lineWidth=2; ctx.stroke(); // draw a ball that the use can move with left/right arrow keys ctx.beginPath(); ctx.arc(ballX,ballY,ballRadius,0,Math.PI*2,false); ctx.closePath(); ctx.fill(); } // Here we just handle command keys function keyDownHandler(event){ // get which key the user pressed var key=event.which; // Let keypress handle displayable characters if(key>46){ return; } switch(key){ case 37: // left key // move the ball 1 left by subtracting 1 from ballX ballX -= 1; // calc the ball's left edge var ballLeft=ballX-ballRadius; // Keep the ball from moving through the left wall if(ballLeft<=leftWall){ ballX=leftWall+ballRadius; } break; case 39: // right key // move the ball 1 right by adding 1 to ballX ballX += 1; // calc the ball's right edge var ballRight=ballX+ballRadius; // Keep the ball from moving through the right wall if(ballRight>=rightWall){ ballX=rightWall-ballRadius; } break; default: break; } // redraw everything draw(); } // Listen for when the user presses a key down window.addEventListener("keydown", keyDownHandler, true); }); // end $(function(){}); </script> </head> <body> <p>Click in the red box to get keyboard focus</p> <p>Then Move ball with left and right arrow keys</p> <canvas id="canvas" width=200 height=150></canvas> </body> </html>
two ball are move diff. side on key board . first ball to move to keyboard to up, down , right, left key second ball move to A(left side), W(up side) ,D(right side) and S(down side). just copy and past in your screen. <html> <head> <title> game</title> </head> <body> <canvas id="canvas" width="307" height= "211" style= "border:1px solid #ff0000 ;" mxrgin = right > </canvas> <script> var x = 10; var x1= 280; var y = 10; var y1 = 10; var dx = 2; var dx1 = 3; var dy = 1; var dy1 =1; var ctx; var ctx1; var WIDTH=300; var HEIGHT=200; var a=""; var b=""; var sp= 500; var timer=[]; var down = []; var up; document.onkeydown=k_down; document.onkeyup=k_up; var left=false; var right=false; var up1=false; var down1=false; var flag=false; var aa=false; init(); function k_down(e) { down[e.keyCode]=true; clearInterval(timer); //sp=10; if(down[37]) { if(sp>2) { sp++; } dy=0; dx=-3; left=true; flag=false; //down=[]; } else if(down[38]) { if(sp>2) { sp++; } dx=0; dy=-4; up1=true; flag=false; //down=[]; } else if(down[39]) { if(sp>2) { sp++; } dy=0; dx=3; right=true; flag=false; //down=[]; } else if(down[40]) { if(sp>2) { sp++; } dx=0; dy=4; down1=true; flag=false; //down=[]; } if(down[65]) { dy1=0; dx1=-3; } else if(down[87]) { dx1=0; dy1=-4; } else if(down[68]) { dy1=0; dx1=3; } else if(down[83]) { dx1=0; dy1=4; } //console.log("speed++>"+sp); timer=setInterval(draw,sp); down[e.keyCode]=false; } function k_up(e) { up=e.keyCode; //alert(sp); if(sp<10) { sp=10; clearInterval(timer); timer=setInterval(draw,10); } //console.log("upp->>"+down); if(left==true && up1==true) { //console.log("1"); sp=2; clearInterval(timer); timer=setInterval(draw,sp); dx=-3; dy=-4; flag=true; } else if(left==true && down1==true) { //console.log("2"); sp=2; clearInterval(timer); timer=setInterval(draw,sp); dx=-3; dy=4; flag=true; } else if(right==true && up1==true) { //console.log("3"); sp=2; clearInterval(timer); timer=setInterval(draw,sp); dx=3; dy=-4; flag=true; } else if(right==true && down1==true) { //console.log("4"); sp=2; clearInterval(timer); timer=setInterval(draw,sp); dx=3; dy=4; flag=true; } if(left==true) { if(flag==false){ dy=0; dx=-3; } } else if(up1==true) { if(flag==false){ dx=0; dy=-4; } } else if(right==true) { if(flag==false){ dy=0; dx=3; } } else if(down1==true) { if(flag==false){ dx=0; dy=4; } } if (up==37) { left=false; } else if (up==38) { up1=false; } else if (up==39) { right=false; } else if (up==40) { down1=false; } } function circle(x,y,r) { ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); } function rect(x,y,w,h) { ctx.beginPath(); ctx.rect(x,y,w,h); ctx.closePath(); ctx.fill(); } function clear() { ctx.clearRect(0, 0, 307, 211); } function init() { //ctx = $("#canvas").getContext("2d"); ctx = document.getElementById('canvas').getContext("2d"); //WIDTH = $("#canvas").width() //HEIGHT = $("#canvas").height() //canvas.addEventListener("click", getPosition, false); return setInterval(draw, 10); } /* function getPosition(event) { // var canvas = document.getElementById("canvas"); // var x = event.x; //var y = event.y; // x -= canvas.offsetLeft; // y -= canvas.offsetTop; //alert("x: " + x + " y: " + y); } */ function draw() { clear(); circle(x, y, 10); circle(x1, y1, 10); if (x + dx > WIDTH || x + dx < 0) dx = -dx; if (y + dy > HEIGHT || y + dy < 0) dy = -dy; x += dx; y += dy; console.log("x->"+x) if (x==10){ dx = -dx; x += dx; y += dy; } if (y==10){ dy = -dy; x += dx; y += dy; } if (x1 + dx1 > WIDTH || x1 + dx1 < 0) dx1 = -dx1; if (y1 + dy1 > HEIGHT || y1 + dy1 < 0) dy1 = -dy1; x1 += dx1; y1 += dy1; console.log("x1->"+x1) if (x1==10){ dx1 = -dx1; x1 += dx1; y1 += dy1; } if (y1==10){ dy1 = -dy1; x1 += dx1; y1 += dy1; } } </script> </body> </html>
Using EaselJS sprite sheet in existing code
I want to modify existing code which uses an image to animate, and use a sprite sheet instead. I'm using the EaselJS library for this. The piece of code that creates the objects for animation: function initStageObjects(){ car = new Car('img/car.png',canvas.width()/2,canvas.height()/2); } And this is the complete code: $(window).load(function(){ $(document).ready(function(){ // Canvas Variables var canvas = $('#canvas'); var context = canvas.get(0).getContext('2d'); var canvasWidth = canvas.width(); var canvasHeight = canvas.height(); // Keyboard Variables var leftKey = 37; var upKey = 38; var rightKey = 39; var downKey = 40; // Keyboard event listeners $(window).keydown(function(e){ var keyCode = e.keyCode; if(keyCode == leftKey){ car.left = true; } else if(keyCode == upKey){ car.forward = true; } else if(keyCode == rightKey){ car.right = true; } else if (keyCode == downKey){ car.backward = true; } }); $(window).keyup(function(e){ var keyCode = e.keyCode; if(keyCode == leftKey){ car.left = false; } else if(keyCode == upKey){ car.forward = false; } else if(keyCode == rightKey){ car.right = false; } else if (keyCode == downKey){ car.backward = false; } }); // Start & Stop button controlls var playAnimation = true; var startButton = $('#startAnimation'); var stopButton = $('#stopAnimation'); startButton.hide(); startButton.click(function(){ $(this).hide(); stopButton.show(); playAnimation = true; updateStage(); }); stopButton.click(function(){ $(this).hide(); startButton.show(); playAnimation = false; }); // Resize canvas to full screen function resizeCanvas(){ canvas.attr('width', $(window).get(0).innerWidth); canvas.attr('height', $(window).get(0).innerHeight); canvasWidth = canvas.width(); canvasHeight = canvas.height(); } resizeCanvas(); $(window).resize(resizeCanvas); function initialise(){ initStageObjects(); drawStageObjects(); updateStage(); } // Car object and properties function Car(src, x, y){ this.image = new Image(); this.image.src = src; this.x = x; this.y = y; this.vx = 0; this.vy = 0; this.angle = 90; this.topSpeed = 5; this.acceleration = 0.1; this.reverse = 0.1; this.brakes = 0.3; this.friction = 0.05; this.handeling = 15; this.grip = 15; this.minGrip = 5; this.speed = 0; this.drift = 0; this.left = false; this.up = false; this.right = false; this.down = false; } // Create any objects needed for animation function initStageObjects(){ car = new Car('img/car.png',canvas.width()/2,canvas.height()/2); } function drawStageObjects(){ context.save(); context.translate(car.x,car.y); context.rotate((car.angle + car.drift) * Math.PI/180); context.drawImage(car.image, -25 , (-47 + (Math.abs(car.drift / 3)))); // context.fillRect(-5, -5, 10, 10); context.restore(); } function clearCanvas(){ context.clearRect(0, 0, canvasWidth, canvasHeight); context.beginPath(); } function updateStageObjects(){ // Faster the car is going, the worse it handels if(car.handeling > car.minGrip){ car.handeling = car.grip - car.speed; } else{ car.handeling = car.minGrip + 1; } // Car acceleration to top speed if(car.forward){ if(car.speed < car.topSpeed){ car.speed = car.speed + car.acceleration; } } else if(car.backward){ if(car.speed < 1){ car.speed = car.speed - car.reverse; } else if(car.speed > 1){ car.speed = car.speed - car.brakes; } } // Car drifting logic if(car.forward && car.left){ if(car.drift > -35){ car.drift = car.drift - 3; } } else if(car.forward && car.right){ if(car.drift < 35){ car.drift = car.drift + 3; } } else if(car.forward && !car.left && car.drift > -40 && car.drift < -3){ car.drift = car.drift + 3; } else if(car.forward && !car.right && car.drift < 40 && car.drift > 3){ car.drift = car.drift - 3; } if(car.drift > 3){ if(!car.forward && !car.left){ car.drift = car.drift - 4; } } else if(car.drift > -40 && car.drift < -3){ if(!car.forward && !car.right){ car.drift = car.drift + 4; } } // General car handeling when turning if(car.left){ car.angle = car.angle - (car.handeling * car.speed/car.topSpeed); } else if(car.right){ car.angle = car.angle + (car.handeling * car.speed/car.topSpeed); } // Use this div to display any info I need to see visually $('#stats').html("Score: 0"); // Constant application of friction / air resistance if(car.speed > 0){ car.speed = car.speed - car.friction; } else if(car.speed < 0) { car.speed = car.speed + car.friction; } // Update car velocity (speed + direction) car.vy = -Math.cos(car.angle * Math.PI / 180) * car.speed; car.vx = Math.sin(car.angle * Math.PI / 180) * car.speed; // Plot the new velocity into x and y cords car.y = car.y + car.vy; car.x = car.x + car.vx; } // Main animation loop function updateStage(){ clearCanvas(); updateStageObjects(); drawStageObjects(); if(playAnimation){ setTimeout(updateStage, 25); } } // Initialise the animation loop initialise(); }); });//]]> // JavaScript Document How could i replace the image being used by the sprite i created?
Even though you maybe could implement a createjs.SpriteSheet into a non-Createjs/non-EaselJS project I would strongly recommend you not to do that, EaselJS-classes where not designed to be used as single modular classes in any kind of project, they best work together in the framework. In the end you probably will need more time and probably end up with more code by trying get everything to work than with just converting your (yet still small) project to EaselJS all together. So learn something new today and refacture your project to EaselJS ;-) but if you want more work, continue reading: A createjs.SpriteSheet basically only handles SpriteSheet data and you can use mySpriteSheet.getFrame(int); to get the image and the source-rect to that frame so you can draw it to your canvas. But a SpriteSheet alone won't handle animations for you, so you would have to advance the "playhead" every frame yourself(go back to frame 0 if at the end ect...), or you can implement another createjs-class called createjs.BitmapAnimation - however, drawing this to your canvas would again require additional code or yet an additional createjs-class: you see where this is getting.
how to move an image on canvas using keyboard arrow key in html5
I m Drawing the image on canvas with this code and it successfully draw the image on canvas now i want to move the image on canvas for that i write the code i check that if the right key of my keyboard is pressed i will increment the x coordinate of an image if left key is pressed i will decrement the x coordinate but image is not moving on the canvas player = new Image(); player.src = "game_character.png"; context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50); how to move an image on canvas var handleInput = function(event, keyState) { switch(event.which) { case 37: { // Left Arrow keyDown.arrowLeft = keyState; break; } case 38: { // Up Arrow keyDown.arrowUp = keyState; break; } case 39: { // Right Arrow keyDown.arrowRight = keyState; break; } case 40: { // Down Arrow keyDown.arrowDown = keyState; break; } } } /** * physics * * This function contains the basic logic for the maze. */ var physics = function() { console.log("physics "); console.log("first condition "+keyDown.arrowRight +player.x+1); if(keyDown.arrowLeft && player.x-1 >= 0 && map[player.y][player.x-1] != 1) { player.x--; redraw = true; } if(keyDown.arrowUp && player.y-1 >= 0 && map[player.y-1][player.x] != 1) { player.y--; redraw = true; } if(keyDown.arrowRight && player.x+1 < map[0].length && map[player.y][player.x+1] != 1) { console.log("arrow right"); player.x++; redraw = true; } if(keyDown.arrowDown && player.y+1 < map.length && map[player.y+1][player.x] != 1) { player.y++; redraw = true; } if(keyDown.arrowRight && player.x+1 >= map[0].length) { player.x++; document.getElementById("canvas_div").style.display="none"; document.getElementById("end_screen_div").style.display="block"; //alert("completed"); } } /** * draw * * This function simply draws the current state of the game. */ var draw = function() { // Don't redraw if nothing has changed if(!redraw) return; context.clearRect(0, 0, cols, rows); context.beginPath(); // Draw the maze for(var a = 0; a < rows; a++) { for(var b = 0; b < cols; b++) { switch(map[a][b]) { case C.EMPTY: context.fillStyle = colors.empty; break; case C.WALL: context.fillStyle = colors.wall; break; } context.fillRect(b * wallDim, a * wallDim, wallDim, wallDim); // x, y, width, height } } // Draw the player /* context.fillStyle = colors.player; context.arc( player.x * wallDim + wallDim / 2, // x position player.y * wallDim + wallDim / 2, // y position wallDim / 2, // Radius 0, // Starting angle Math.PI * 2, // Ending angle true // antiClockwise );*/ player = new Image(); player.src = "game_character.png"; context.drawImage(player,player.x * wallDim + wallDim ,player.y * wallDim + wallDim ,50,50); var firstplayer=new Image(); firstplayer.src="top_character01.png"; context.drawImage(firstplayer,680,0,60,60); var secondplayer= new Image(); secondplayer.src="top_character02.png"; context.drawImage(secondplayer,750,0,60,60); context.fill(); context.closePath(); redraw = false; }
In your draw method, you reinitialize the player each time : player = new Image(); player.src = "game_character.png"; So you erase the player.x modified by your event handler. You should initialize the player only once, outside the draw function. You can move the initialization like this : var player = new Image(); player.src = "game_character.png"; var draw = function() { There is absolutely no need to call player.src = "game_character.png"; inside the draw function. As a general rule, when dealing with animation, try to remove all what you can from the draw function, which should be as fast as possible.
You will need to redraw the canvas each time. Something like this: function init() { canvas = document.getElementById("canvas"); context = canvas.getContext("2d"); x = canvas.width / 2; //align to centre of the screen y = canvas.height / 2; //same as above speed = 5; //speed for the player to move at width = 50; //width of the player height = 50; //height of the player playerimage = new Image(); playerimage.src = "path/to/image/for/player"; //path to the image to use for the player canvas.addEventListener("keypress", update); } function update(event) { if (event.keyCode == 38) { y -= speed; //going up } if (event.keyCode == 40) { y += speed; //going down } if (event.keyCode == 37) { x -= speed; //going left } if (event.keyCode == 39) { x += speed; //going right } render(); } function render() { context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(playerimage, x, y, width, height); } I haven't tested it, so I don't know whether it works and there may be some mistakes here and there. It should work though! If nothing else, it will (hopefully) give you an idea of one way in which you can go about doing it...