Moving object to targets within an array on the canvas - javascript

I have some P5js code that I made.
It basically moves the circle around the screen to predetermined targets stored in an array. I will be using it within my game that uses A* pathfinding and stores the path points in an array. I then am looking at moving the player to each of those points smoothly with the code below.
What I am asking
Most importantly, can this code be optimized/cleaner if so, how?
How can I allow for a larger speed value. Currently if I change the speed to 3, it doesnt trigger the if statement (I would need to cicle to be at the target within a 1 px varience regardless of spped).
Other notes
I tried using the P5 Lerp function however it did not allow for a constant movement speed.
Thank you :)
var targets
var target_index = 0
var position
var x_complete = true
var y_complete = true
var speed = 1
function setup() {
createCanvas(400, 400);
targets = [createVector(0, 0), createVector(50, 50), createVector(0, 0), createVector(0, 50), createVector(200, 200)]
position = targets[0]
}
var count = 0;
function draw() {
background(220);
move_c()
draw_c()
}
function draw_c() {
strokeWeight(10);
point(position.x, position.y);
}
function move_c() {
var x_needs_to_goes_up
var x_is_currently_smaller
var y_needs_to_goes_up
var y_is_currently_smaller
x_complete = false
y_complete = false
if (targets.length - 1 > target_index) {
x_needs_to_goes_up = !number_is_larger(targets[target_index].x, targets[target_index + 1].x) //X goes up
x_is_currently_smaller = number_is_smaller(targets[target_index].x, targets[target_index + 1].x)
y_needs_to_goes_up = !number_is_larger(targets[target_index].y, targets[target_index + 1].y) //X goes up
y_is_currently_smaller = number_is_smaller(targets[target_index].y, targets[target_index + 1].y)
if (x_needs_to_goes_up && x_is_currently_smaller) { //If x is currently smaller then target
move_x(true)
} else if (x_needs_to_goes_up && !x_is_currently_smaller) {
x_complete = true
}
if (!x_needs_to_goes_up && !x_is_currently_smaller) { //If x is currently smaller then target
move_x(false)
} else if (!x_needs_to_goes_up && x_is_currently_smaller) {
x_complete = true
}
if (y_needs_to_goes_up && y_is_currently_smaller) { //If x is currently smaller then target
move_y(true)
} else if (y_needs_to_goes_up && !y_is_currently_smaller) {
y_complete = true
}
if (!y_needs_to_goes_up && !y_is_currently_smaller) { //If x is currently smaller then target
move_y(false)
} else if (!y_needs_to_goes_up && y_is_currently_smaller) {
y_complete = true
}
if (y_complete && x_complete) {
target_index++
}
}
}
function move_y(up) {
if (up) {
position = createVector(targets[target_index].x, targets[target_index].y += speed)
} else {
position = createVector(targets[target_index].x, targets[target_index].y -= speed)
}
}
function move_x(up) {
if (up) {
position = createVector(targets[target_index].x += speed, targets[target_index].y)
} else {
position = createVector(targets[target_index].x -= speed, targets[target_index].y)
}
}
function number_is_larger(num1, num2) {
return num1 > num2 ? true : false
}
function number_is_smaller(num1, num2) {
return num1 < num2 - 1 ? true : false
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

The main problem in your code is that when you increase the speed you shoot over the target as you may not hit the target accurately.
First of all the initial position vector should be a copy of the first target:
position = targets[0].copy()
Calculate the vector from the position to the next target and the Euclidean lenght of the vector (this is the distance of the position to the next target:
let direction = p5.Vector.sub(targets[target_index], position)
let distance = direction.mag()
Distinguish whether the distance to the next target is greater or less than the speed:
if (distance <= speed) {
// less
// [...]
} else {
// greater
// [...]
}
If it is less, the next position is the next target and the target index need to be incremented:
position = targets[target_index].copy()
target_index ++;
If it is greater, make on step forwards. Calculate the normalized direction vector. A normalized vector is a Unit vector and has a length of 1. Multiply the vector with the speed. Now the vector is length the speed. Add the vector to the position:
position.add(direction.normalize().mult(speed))
var targets
var target_index = 0
var position
var speed = 3
function setup() {
createCanvas(400, 400);
targets = [createVector(0, 0), createVector(50, 50), createVector(0, 0), createVector(0, 50), createVector(200, 200)]
position = targets[0].copy()
}
function draw() {
background(220);
move_c()
draw_c()
}
function draw_c() {
strokeWeight(10);
point(position.x, position.y);
}
function move_c() {
if (targets.length - 1 > target_index) {
let direction = p5.Vector.sub(targets[target_index], position)
let distance = direction.mag()
if (distance <= speed) {
position = targets[target_index].copy()
target_index ++;
} else {
position.add(direction.normalize().mult(speed))
}
} else {
target_index = 0
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

Related

How would I make a collider that stops the game when it collides with the "character"?

I'm still pretty new to this, so I don't know how to create a collider. My end goal is to have a game like the chrome dinosaur game. Same principles, and all. My question is, though, how do I even make a collider. I will be using a .gif for the "dinosaur". I'd like to make it where if this collider were to touch another collider, the game stops and a "game over" is shown. I have tried to create a collider, but they just keep showing up underneath the screen where the game is shown. Ant tips, tricks, or advice? Thanks
Code is as follows:
let img; //background
var bgImg; //also the background
var x1 = 0;
var x2;
var scrollSpeed = 4; //how fast background is
let music; //for music
let catBus; //catbus
//collider variables
let tinyToto;
let tiniestToto;
let hin;
let totoWithBag;
let noFace;
let happySoot;
var mode; //determines whether the game has started
let gravity = 0.2; //jumping forces
let velocity = 0.1;
let upForce = 7;
let startY = 730; //where cat bus jumps from
let startX = 70;
let totoX = 900;
let totoY = 70;
let tinToX = 900;
let tinToY = 70;
var font1; //custom fonts
var font2;
p5.disableFriendlyErrors = true; //avoids errors
function preload() {
bgImg = loadImage("backgwound.png"); //importing background
music = loadSound("catbus theme song.mp3"); //importing music
font1 = loadFont("Big Font.TTF");
font2 = loadFont("Smaller Font.ttf");
//tinyToto.setCollider("rectangle",0,25,75,75)
}
function setup() {
createCanvas(1000, 1000); //canvas size
img = loadImage("backgwound.png"); //background in
x2 = width;
music.loop(); //loops the music
catBus = {
//coordinates for catbus
x: startX,
y: startY,
};
/*
tinyToto = {
x: totoX,
y: totoY,
}
tinTo = {
x : tinToX,
y: tinToY,
}
*/
catGif = createImg("catgif.gif"); //creates catbus
catGif.position(catBus.x, catBus.y); //creates position
catGif.size(270, 100); //creates how big
/*
tinyToto = createImg("TinyToto.gif")
tinyToto.position(tinyToto.x, tinyToto.y)
tinyToto.size(270,100)
tiniestTo = createImg("tiniest Toto.gif")
tiniestTo.position(tinToX.x, tinToY.y)
tiniestTo.size(270,100)
*/
mode = 0; //game start
textSize(50); //text size
}
function draw() {
let time = frameCount; //start background loop
image(img, 0 - time, 0);
image(bgImg, x1, 2, width, height);
image(bgImg, x2, 2, width, height);
x1 -= scrollSpeed;
x2 -= scrollSpeed;
if (x1 <= -width) {
x1 = width;
}
if (x2 <= -width) {
x2 = width;
} //end background loop
fill(128 + sin(frameCount * 0.05) * 128); //text colour
if (mode == 0) {
textSize(20);
textFont(font1);
text("press SPACE to start the game!", 240, 500); //what text to type
}
fill("white");
if (mode == 0) {
textSize(35);
textFont(font2);
text("CATBUS BIZZARE ADVENTURE", 90, 450); //what text to type
}
catBus.y = catBus.y + velocity; //code for jumping
velocity = velocity + gravity;
if (catBus.y > startY) {
velocity = 0;
catBus.y = startY;
}
catGif.position(catBus.x, catBus.y);
//setCollider("tinyToto")
}
function keyPressed() {
if (keyCode === 32 && velocity == 0) {
//spacebar code
mode = 1;
velocity += -upForce;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
well, this is how I would generally do that kind of thingy:
function draw(){
for(let i in objects) // objects would be cactuses or birds
if(objects[i].x > player.x &&
objects[i].x < player.x + player.width &&
objects[i].y > player.y &&
objects[i].y < player.y + player.height){
noLoop()
// maybe do something else here
} // you could also use: for(let object of objects)
}
or if you want to do class stuff:
let player = new Player()
class Entity {
hasCollided_pointRect(_x, _y, _width, _height){
if(this.x > _x &&
this.x < _x + _width &&
this.y > _y &&
this.y < _y + _height){
return true
}
}
}
class Cactus extends Entity {
update(){
if(hasCollided_pointRect(player.x, player.y, player.width, player.height))
lossEvent()
}
}
class Player {
// ...
}
function lossEvent(){
noLoop()
}
this is a pretty classy way to do it and for a small game you really don't need all of this
also MDN has a nice article on rect with rect & point with rect collisions,
point with point collision is just (x == x && y == y)
https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
this is one of my recent loss "functions":
if(flag.health <= 0){
noLoop()
newSplashText("You lost!\nPress F5 to restart!", "center", "center", 1)
}
The way I handled game states in my Processing games was by making seperate classes for them. Then my main sketch's draw function looked something like
fun draw()
{
currentState.draw();
}
Each gamestate then acted as their own sketches (for example a menu screen, playing, game over, etc), and had a reference to the main sketch which created the states. They would then alter the main's currentState to, i.e., a new GameOverState() etc. where needed.
For now, don't worry about doing that too much if all you want a really simple gameoverscreen with an image and some text.
I would suggest a structure like this instead. Use this pseudocode in your main draw function:
fun draw()
{
if (gameOver)
{
// show game over screen
img(gameOver);
text("game over!");
// skip rest of the function
return;
}
// normal game code goes here
foo();
bar();
// update game over after this frame's game code completes
gameOver = checkGameOver();
}
Now you need a way of checking for a collision to determine the result of checkGameOver()
For the collision handling, check out Jeffrey Thompson's book/website on collision handling. It's an amazing resource, I highly recommend you check it out.
From the website I just linked, here's an excerpt from the website talking about handling collisions between 2d rectangles.
And here's a modified version of the collision handling function listed there (I updated the variable names to be a little more intuitive)
boolean rectRect(float rect1X, float rect1Y, float rect1Width, float rect1Height, float rect2X, float rect2Y, float rect2Width, float r2h)
{
// are the sides of one rectangle touching the other?
if (rect1X + rect1Width >= rect2X && // r1 right edge past r2 left
rect1X <= rect2X + rect2Width && // r1 left edge past r2 right
rect1Y + rect1Height >= rect2Y && // r1 top edge past r2 bottom
rect1Y <= rect2Y + r2h)
{ // r1 bottom edge past r2 top
return true;
}
return false;
You can use that function in your checkGameOver() function which would return a bool depending on whether your collision criteria are met.
For your game, you would loop over every obstacle in your game and check whether the dino and the obstacle overlap.
Pseudocode:
boolean checkGameOver()
{
foreach (Obstacle obstacle in obstacles)
{
if (rectRect(dino, obstacle))
{
return true;
}
}
return false;
}

Enemy detection and turret animation/control in a JavaScript p5.js game

I'm making a tower defense game using JavaScript and p5.js library. My enemy follows a path and their location is always stored in a list. I have a base and a gun, the gun rotates around the base(as 1 unit) and is supposed to point towards the nearest enemy. I have a function that will allow me to make the gun point towards the enemy pointEnemy however, I'm not able to get the correct condition to make it point towards the nearest enemy in it's range. I need the correct argument for enemyx & enemyy. I'm currently spawning 100 enemies and they keep moving, their location is stored in globalenemy1position. Any help is appreciated, thank you.
Required Code
Some important variables
var numberOfEnemy1 = 100
let classenemy1 = new Enemy1(numberOfEnemy1);
var globalenemy1position = [];
var isFireTowerPressed = false;
var FireTowerPos = []; // Position of all FireTowers => [x,y]
var FireTowerRange = 300;
var FireTowerAngle = 0;
My Enemy Class
class Enemy1
{
constructor(number_of_enemies)
{
this.number_of_enemies = number_of_enemies;
this.enemy_position = [];
this.enemy1speed = 4;
}
enemy1_spawn()
{
let randomx = random(-300, -100);
for(var i=0; i<this.number_of_enemies; i++)
{
var positionx = randomx;
var positiony = 100;
this.enemy_position.push([positionx + (-i*50), positiony]);
globalenemy1position.push([positionx + (-i*50), positiony]);
image(enemy1, this.enemy_position[i][0], this.enemy_position[i][1]);
}
}
enemy1_move()
{
for(var i = 0; i < this.enemy_position.length; i++)
{
image(enemy1, this.enemy_position[i][0], this.enemy_position[i][1]);
if (this.enemy_position[i][0] >= 200 && this.enemy_position[i][1] <= 450 && this.enemy_position[i][0] < 599)
{
this.enemy_position[i][1] += this.enemy1speed;
globalenemy1position[i][1] += this.enemy1speed;
}
else if (this.enemy_position[i][1] >= 100 && this.enemy_position[i][0] >= 600)
{
this.enemy_position[i][1] -= this.enemy1speed;
globalenemy1position[i][1] -= this.enemy1speed;
}
else if (this.enemy_position[i][0] >= 750)
{
this.enemy_position[i][0] = 750;
lives --;
this.enemy_position.shift();
globalenemy1position.shift();
}
else
{
this.enemy_position[i][0] += this.enemy1speed;
globalenemy1position[i][0] += this.enemy1speed;
}
}
}
}
Draw Function - Redraws Every Frame
function draw()
{
background(60, 238, 161);
[...]
classenemy1.enemy1_move();
rect(750, 70, 50, 100);
ShowLives();
if (isFireTowerPressed == true)
{
image(firetowerbaseImg, mouseX - 28, mouseY - 28);
noFill();
stroke(0,0,0);
strokeWeight(1);
circle(mouseX, mouseY, 300);
}
for (var i = 0; i < FireTowerPos.length; i++)
{
image(firetowerbaseImg, FireTowerPos[i][0], FireTowerPos[i][1]);
if (globalenemy1position.length >= 1)
{
var gunx = FireTowerPos[i][0] +28;
var guny = FireTowerPos[i][1]+25;
var gunrange = FireTowerPos[i][3];
for (j=0; j<globalenemy1position.length; j++)
{
// Need help with this statement here
pointEnemy(globalenemy1position[j][0], globalenemy1position[j][1], gunx, guny, FireTowerPos[i][2], FireTowerPos[i][3]);
}
}
else
{
image(firetowerturretImg, FireTowerPos[i][0], FireTowerPos[i][1]-20);
}
}
}
Function to make the gun point towards Enemy - I need the proper value for enemyx & enemyy
function pointEnemy(enemyx, enemyy, gunx, guny, gunangle, gunrange)
{
const isWithinRange = dist(enemyx, enemyy, gunx, guny) < gunrange;
if(isWithinRange)
{
gunangle = atan2(enemyy - guny, enemyx - gunx) + radians(90);
}
push();
translate(gunx, guny);
// rect(-25, -20, 50, 40) // Draw the gun base
// ellipse(0, 0, gun.range*2) // display the gun range
rotate(gunangle);
image(firetowerturretImg, -28, -45); // Set the offset of the gun sprite and draw the gun
pop();
}
Here is a picture to help visualise the problem
As you can see, currently I'm just iterating through all the enemies and giving their location, so it's basically pointing to every enemy nearby.
Updates
1
I tried the approach given by #user3386109 , but wasn't able to implement it, also if possible I want the turret/gun to point towards the enemy till it leaves the range and not always point towards the closest enemy. It should start off with the closest and then keep pointing towards it till it leaves or the enemy dies(position removed from the list), whichever comes first. The function should then restart again and continue the process.
This process is the complete aiming for the tower. Add this to draw and it searches for enemies.
for (var i = 0; i < FireTowerPos.length; i++)
{
// image(firetowerbaseImg, FireTowerPos[i][0], FireTowerPos[i][1]);
// pointEnemy(mouseX, mouseY, FireTowerPos[i][0] +28, FireTowerPos[i][1]+25, FireTowerPos[i][2], FireTowerPos[i][3]);
image(firetowerbaseImg, FireTowerPos[i][0], FireTowerPos[i][1]);
var enemiesInRange = [];
let firetowerx = FireTowerPos[i][0];
let firetowery = FireTowerPos[i][1];
for (var j = 0; j < globalenemy1position.length; j++)
{
var checkDist = dist(globalenemy1position[j][0], globalenemy1position[j][1], firetowerx, firetowery);
let thisenemyx = globalenemy1position[j][0];
let thisenemyy = globalenemy1position[j][1];
if (checkDist < FireTowerRange)
{
enemiesInRange.push([thisenemyx, thisenemyy]);
pointEnemy(enemiesInRange[0][0], enemiesInRange[0][1], FireTowerPos[i][0] +28, FireTowerPos[i][1]+25, FireTowerPos[i][2], FireTowerPos[i][3]);
}
else
{
enemiesInRange.shift();
}
}
}

Smooth character movement on an Isometric map

I have an Isometric engine that I am building:
http://jsfiddle.net/neuroflux/09h43kz7/1/
(Arrow keys to move).
I am updating the Engine.player.x and Engine.player.y to move the character, but (obviously) the player just "pops" from one tile to another.
I wondered if there was a way to make him "slide" from tile to tile?
Or better still, free movement...
I've been pulling my hair out trying.
Here's the relevant code:
var Engine = {
// canvas variables
canvas: null,
ctx: null,
// map
map: [
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
[2,1,1,1,1,1,1,1,1,1,1,1,1,1,2],
[2,1,1,0,0,1,1,1,1,0,0,0,1,1,2],
[2,2,1,0,0,0,0,1,0,0,0,0,1,1,2],
[2,2,1,1,1,1,0,0,0,0,1,0,0,1,2],
[2,2,2,2,2,1,0,0,0,1,0,0,0,1,2],
[2,2,1,1,1,1,0,0,0,0,0,0,0,1,2],
[2,1,1,0,1,0,0,0,0,1,1,0,0,1,2],
[2,1,0,0,0,0,0,1,0,0,0,0,0,1,2],
[2,1,0,0,0,0,0,0,0,0,1,0,0,1,2],
[2,1,0,0,0,0,1,0,0,0,0,0,0,1,2],
[2,1,0,1,1,0,0,0,0,1,0,0,0,1,2],
[2,1,0,0,0,0,0,0,0,0,1,0,1,1,2],
[2,1,1,1,1,1,1,1,1,1,1,1,1,1,2],
[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
],
// player info
player: {
x:1,
y:1
},
// tile size
tileH: 31,
tileW: 63,
// map position
mapX: window.innerWidth/2,
mapY: window.innerHeight/3,
// tile images
tileSources: [
"images/stone.png",
"images/grass.png",
"images/water.png",
"images/ralph.png"
],
// for pre-loading
tileGraphics: [],
tilesLoaded: 0,
// image preloader
loadImages: function() {
for (var i = 0; i < Engine.tileSources.length; i++) {
Engine.tileGraphics[i] = new Image();
Engine.tileGraphics[i].src = Engine.tileSources[i];
Engine.tileGraphics[i].onload = function() {
Engine.tilesLoaded++;
if (Engine.tilesLoaded === Engine.tileSources.length) {
Engine.draw();
}
}
}
},
// update logic
update: function() {
Engine.draw();
},
// draw the scene
draw: function() {
Engine.ctx.clearRect(0, 0, Engine.canvas.width, Engine.canvas.height);
var drawTile;
for (var i = 0; i < Engine.map.length; i++) {
for (var j = 0; j < Engine.map[i].length; j++) {
drawTile = Engine.map[i][j];
Engine.ctx.drawImage(Engine.tileGraphics[drawTile], (i - j) * Engine.tileH + Engine.mapX, (i + j) * Engine.tileH / 2 + Engine.mapY);
if (Engine.player.x === i && Engine.player.y === j) {
Engine.ctx.drawImage(Engine.tileGraphics[3], (i - j) * Engine.tileH + Engine.mapX, (i + j) * Engine.tileH / 2 + Engine.mapY - Engine.tileH + 10);
}
}
}
Engine.gameLoop();
},
// game loop
gameLoop: function() {
Engine.gameTimer = setTimeout(function() {
requestAnimFrame(Engine.update, Engine.canvas);
}, 1);
},
// start
init: function() {
Engine.canvas = document.getElementById("main");
Engine.canvas.width = window.innerWidth;
Engine.canvas.height = window.innerHeight;
Engine.ctx = Engine.canvas.getContext("2d");
document.addEventListener("keyup", function(e) {
//console.log(e.keyCode);
switch(e.keyCode) {
case 38:
if (Engine.map[Engine.player.x-1][Engine.player.y] !== 2) {
Engine.player.x--;
}
break;
case 40:
if (Engine.map[Engine.player.x+1][Engine.player.y] !== 2) {
Engine.player.x++;
}
break;
case 39:
if (Engine.map[Engine.player.x][Engine.player.y-1] !== 2) {
Engine.player.y--;
}
break;
case 37:
if (Engine.map[Engine.player.x][Engine.player.y+1] !== 2) {
Engine.player.y++;
}
break;
}
});
Engine.loadImages();
}
}
// loaded
window.onload = function() {
Engine.init();
};
// request animation frame
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element){
fpsLoop = window.setTimeout(callback, 1000 / 60);
};
}());
Thanks in advance!
You are drawing the character at tile positions. What you want is to just add a second set of coordinates for the character representing its destination. To move smoothly you can set the characters position in fractions of a tile. Eg player.x = 2.5 the character is halfway between tiles 2 and 3.
Also you want to get rid of the messing about in isometric space. Off load the transformation from 2d to isometric to the draw function, rather than doing it by hand each time you draw to the playfield.
Create the draw function
// add to the Engine object.
// img is the image to draw. x and y are the tile locations.
// offsetX and offsetY [optional] are pixel offsets for fine tuning;
drawImageIso:function (img,x,y,offsetX,offsetY){
offsetX = offsetX === undefined ? 0: offsetX; // so you dont have to
offsetY = offsetY === undefined ? 0: offsetY; // add the offset if you
// are not using it;
Engine.ctx.drawImage( // draw the image
img,
(x - y) * Engine.tileH + Engine.mapX + offsetX,
(x + y) * Engine.tileH / 2 + Engine.mapY - Engine.tileH+offsetY
);
},
Change the player object to
player: {
x:1,
y:1,
destX:1, // the destination tile
destY:1,
playerAtDest:true, // true if the player has arrived
},
Add this befor the tile render loops
var p = Engine.player; // because I am lazy and dont like typing.
var dx = p.destX;
var dy = p.destY;
var maxPlayerSpeed = 0.1; // max speed in tiles per frame
var mps = maxPlayerSpeed; // because I am lazy
// check if the player needs to move
if( Math.abs(p.x - dx) > mps || Math.abs(p.y - dy) > mps ){
p.x += Math.max( -mps , Math.min( mps , dx - p.x )); // move to destination clamping speed;
p.y += Math.max( -mps , Math.min( mps , dy - p.y ));
p.playerAtDest = false; // flag the player is on the way
}else{
// player directly over a till and not moving;
p.x = dx; // ensure the player positioned correctly;
p.y = dy;
p.playerAtDest = true; // flag the player has arrived
}
Add the following where you used to draw the player. Use the destination x,y to determine when to draw or use Math.round(Engine.player.x) and y to determine when.
// now draw the player at its current position
Engine.drawImageIso( Engine.tileGraphics[3] , p.x , p.y , 0 , 10);
You will have to change the interface to move player destination rather than x and y. You may also want to delay the move until the player has arrived at the current destination.
That covers the basics.

identify an object on canvas by a click event

Into this simple code I use an eventListener which doesn't look to work at all. The canvas display an image and the given hitpaint() function is supposed determines whether a click occurs. I cant understand why the eventListener behaves like that. Any insight would be helpful.
mycanv.addEventListener("click", function(e) {
var output = document.getElementByID("output");
ctx.fillStyle = 'blue';
//ctx.clearRect(0,0,100,20);
if (hitpaint) {
//ctx.fillText("hit",100,20);
output.innerHTML = "hit";
} else {
//ctx.fillText("miss",100,20);
output.innerHTML = "miss";
}
}, false);
The hitpaint() function is defined as:
function hitpaint(mouse_event) {
var bounding_box = mycanv.getBoundingClientRect();
var mousex = (mouse_event.clientX - bounding_box.left) *
(mycanv.width / bounding_box.width);
var mousey = (mouse_event.clientY - bounding_box.top) *
(mycanv.height / bounding_box.height);
var pixels = ctx.getImageData(mousex, mousey, 1, 1);
for (var i = 3; i < pixels.data.length; i += 4) {
// If we find a non-zero alpha we can just stop and return
// "true" - the click was on a part of the canvas that's
// got colour on it.
if (pixels.data[i] !== 0) return true;
}
// The function will only get here if none of the pixels matched in
return false;
}
Finally, the main loop which display the picture in random location into the canvas:
function start() {
// main game function, called on page load
setInterval(function() {
ctx.clearRect(cat_x, cat_y, 100, 100);
cat_x = Math.random() * mycanv.width - 20;
cat_y = Math.random() * mycanv.height - 20;
draw_katy(cat_x, cat_y);
}, 1000);
}
There are a some issues here:
As Grundy points out in the comment, the hitpaint is never called; right now it checks for it's existence and will always return true
The mouse coordinates risk ending up as fractional values which is no-go with getImageData
Scaling the mouse coordinates is usually not necessary. Canvas should preferably have a fixed size without an additional CSS size
Add boundary check for x/y to make sure they are inside canvas bitmap
I would suggest this rewrite:
mycanv.addEventListener("click", function(e) {
var output = document.getElementByID("output");
ctx.fillStyle = 'blue';
//ctx.clearRect(0,0,100,20);
if (hitpaint(e)) { // here, call hitpaint()
//ctx.fillText("hit",100,20);
output.innerHTML = "hit";
} else {
//ctx.fillText("miss",100,20);
output.innerHTML = "miss";
}
}, false);
Then in hitpaint:
function hitpaint(mouse_event) {
var bounding_box = mycanv.getBoundingClientRect();
var x = ((mouse_event.clientX - bounding_box.left) *
(mycanv.width / bounding_box.width))|0; // |0 cuts off any fraction
var y = ((mouse_event.clientY - bounding_box.top) *
(mycanv.height / bounding_box.height))|0;
if (x >= 0 && x < mycanv.width && y >= 0 && y < mycanv.height) {
// as we only have one pixel, we can address alpha channel directly
return ctx.getImageData(x, y, 1, 1).data[3] !== 0;
}
else return false; // x/y out of range
}

JS 2D collision rectangle with map

I have a player of 50 width and 30 height. My problem is calculating the collision correctly. I figured how to do this by checking the middle of the player (you can see it below), but I have problem with accounting for his width and height as well - half of him will go through the wall before he stops.
The map is divided into many squares (for example 100x100 pixels, the 100 is called tileSize) and between the squares there either is a wall or isn't (each square is an object which can have top or/and left true, when true, you cannot pass that side of the square - there is a wall).
the collision detection (item == player):
//inner walls - map collisions
var tileX = Math.floor(item.pos.x / this.tileSize);
var tileY = Math.floor(item.pos.y / this.tileSize);
var tileX = Math.floor(item.pos.x / this.tileSize);
var tileY = Math.floor(item.pos.y / this.tileSize);
if(tileX == item.last_X && tileY == item.last_Y){return;} //if its the same tile..
var colidedX = false;
var colidedY = false;
/* Check X */
if (item.last_X > tileX) {
if (this.map[item.last_Y][item.last_X].left) {
item.pos.x = item.last_X * this.tileSize;
colidedX = true;
}
}
if (item.last_X < tileX) {
if (this.map[item.last_Y][item.last_X+1].left) {
item.pos.x = (item.last_X+1) * this.tileSize;
colidedX = true;
}
}
/* Check Y */
if (item.last_Y > tileY) {
if (this.map[item.last_Y][item.last_X].top) {
item.pos.y = item.last_Y * this.tileSize;
colidedY = true;
}
}
if (item.last_Y < tileY) {
if (this.map[item.last_Y+1][item.last_X].top) {
item.pos.y = (item.last_Y+1) * this.tileSize;
colidedY = true;
}
}
if(colidedX == false){
item.last_X = tileX;
}
if(colidedY == false){
item.last_Y = tileY;
}
I have an idea how I could do it, but it would be very complicated and long, so I thought there must be a simpler way to do this.

Categories