Target Smooth Following [duplicate] - javascript

This question already has an answer here:
Comparing x/y of two positions on a canvas
(1 answer)
how to make a canvas element follow another canvas element smoothly at the same speed [duplicate]
Closed 6 years ago.
I'm wondering today how to make a canvas element follow another canvas element smoothly. For example, I'm trying to make a game where a canvas element continually follows the player (which can be moved using W, A, S, & D) smoothly. I had an idea to use the Pythagorean theorem to check for the closest & fastest way to move from Point A (the canvas element) to Point B (the player). However, I have no physical way to do this. Does anyone have any ideas or answers of how I could make a canvas element constantly follow a player as smoothly as possible so it reaches the player the fastest?
Here I have an example of a very bad way of following:
<!DOCTYPE html>
<html>
<head>
<title>Target Following Test</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<center>
<canvas id="canvas" width="800" height="500"></canvas>
</center>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function(x, y, radius, fillCircle, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}
//Moving Obstacle
var Obstacle = function(x, y) {
this.x = x;
this.y = y;
this.vSpeed = 0;
this.hSpeed = 0;
}
Obstacle.prototype.drawOb = function(color) {
drawRect(this.x, this.y, "Red")
}
Obstacle.prototype.follow = function() {
this.y += this.vSpeed
this.x += this.hSpeed
if (this.x < ball.x - 9) {
this.hSpeed = 1;
}
if (this.x > ball.x - 10) {
this.hSpeed = -1;
}
if (this.y > ball.y - 10) {
this.vSpeed = -1;
}
if (this.y < ball.y - 9) {
this.vSpeed = 1;
}
}
Obstacle.prototype.checkCollision = function(direction) {
return (ball.x - ball.radius < this.x + 20) &&
(ball.x + ball.radius > this.x) &&
(ball.y - ball.radius < this.y + 20) &&
(ball.y + ball.radius > this.y);
}
// The Ball constructor
var Ball = function() {
this.x = 20
this.y = 20
this.xSpeed = 0;
this.ySpeed = 0;
this.radius = 10;
};
// Draw the ball at its current position
Ball.prototype.draw = function() {
circle(this.x, this.y, 10, true, "Black");
};
Ball.prototype.reposition = function(reX, reY) {
this.x = reX;
this.y = reY;
}
// Update the ball's position based on its speed
Ball.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Set the ball's direction based on a string
Ball.prototype.setDirection = function(direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -2;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 2;
} else if (direction === "left") {
this.xSpeed = -2;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 2;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
function simulate() {
var prev_ball_x = ball.x;
var prev_ball_y = ball.y;
var prev_fol_x = follower.x;
var prev_fol_y = follower.y;
ball.move();
follower.follow()
if (follower.checkCollision()) {
ball.setDirection('stop');
follower.vSpeed = 0;
follower.hSpeed = 0;
follower.x = prev_fol_x;
follower.y = prev_fol_y;
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
}
function draw() {
ctx.clearRect(0, 0, width, height);
ball.draw();
follower.drawOb();
ctx.strokeRect(0, 0, width, height);
}
// An object to convert keycodes into action names
var keyActions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function(event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
$("body").keyup(function(event) {
ball.setDirection('stop');
})
setInterval(function() {
// separate drawing and simulating phases
simulate();
draw();
}, 10);
// Create all the Objects!
var ball = new Ball();
var follower = new Obstacle(400, 100);
</script>
</body>
</html>

Note: i haven't really inspected your code...
But hopefully I understand your question correctly. And if I do, the solution could be pretty simple.
The most simple and fast way is to move the canvas element in a straight line to the player, without the help of mr Pythagoras. For that you need to know the player's position (x, y), which you do.
I took an easing function from an AS3 question, but it's the same for JS: AS 3 simple ease
On every update, ease the follower to the position of the player:
follower.x += (player.x - follower.x) / delay;
follower.y += (player.y - follower.y) / delay;
Example: Fiddle
It isn't a drop-in fix for your script, but hopefully it's helpful

Related

Player glitches through left side of horizontal moving block

EDIT: I rewrote a minimal reproducible example in p5.js, so you can see what's happening here:
let keyInput = []
let player
let block
function setup() {
createCanvas(600, 600)
player = new Player(0, height/2)
block = new Block(200, height-100, 100, 1000)
}
function draw() {
background(220);
player.draw()
block.draw()
player.moveX()
block.checkCollisionsX()
player.moveY()
block.checkCollisionsY()
}
function keyPressed() {
keyInput[keyCode] = true;
}
function keyReleased() {
keyInput[keyCode] = false;
}
function rectCollide(x1, y1, w1, h1, x2, y2, w2, h2) {
return x1 + w1 > x2 && x1 < x2 + w2 && y1 + h1 > y2 && y1 < y2 + h2;
}
//BLOCK CONSTRUCTOR
class Block {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.movingSpeed = 3;
this.start = 200
this.stop = 400
}
draw() {
fill(255)
rect(this.x, this.y, this.w, this.h)
this.x += this.movingSpeed;
if (this.x > this.stop) {
this.movingSpeed = -this.movingSpeed;
}
if (this.x < this.start) {
this.movingSpeed = abs(this.movingSpeed);
}
}
checkCollisionsX() {
if (rectCollide(player.pos.x, player.pos.y, player.width, player.height, this.x, this.y, this.w, this.h)) {
if (player.vel.x < 0) { // If the player moved left and collided with the right side of block
player.pos.x = this.x + this.w;
} else { // If the player moved right and collided with the left side of block
player.pos.x = this.x - player.width;
}
player.vel.x = 0;
}
}
checkCollisionsY() {
if (rectCollide(player.pos.x, player.pos.y, player.width, player.height, this.x, this.y, this.w, this.h)) {
if (player.vel.y < 0) {
player.pos.y = this.y + this.h;
player.vel.y *= -yRebound; // Not -1 because collisions are not perfectly elastic
} else {
//player.pos.x += movingSpeed; //Keep player on platform while platform is moving
player.jumps = player.numJumps;
player.pos.y = this.y - player.height;
player.vel.y = 0;
player.acc.y = 0;
}
}
}
}
//PLAYER CONSTRUCTOR
class Player {
constructor(x, y) {
this.width = 50
this.height = 100
// all 3 chars for pretty code
this.pos = new p5.Vector(x, y);
this.vel = new p5.Vector(0, 0);
this.acc = new p5.Vector(0, 0);
this.accSpeed = 0.05;
this.gravity = 0.5;
this.maxVel = 10;
this.jumpForce = 15;
this.friction = 0.15;
this.numJumps = 1;
this.jumps = this.numJumps;
this.isGrounded = false;
this.canMove = true;
this.dir = "DOWN"
}
draw() {
fill(255, 0, 0)
rect(this.pos.x, this.pos.y, this.width, this.height)
}
moveX() {
//MOVE X
if (keyInput[LEFT_ARROW] && this.vel.x > -this.maxVel && this.canMove) {
this.acc.x = -this.accSpeed;
} else if (keyInput[RIGHT_ARROW] && this.vel.x < this.maxVel && this.canMove) {
this.acc.x = this.accSpeed;
} else if (abs(this.vel.x) > 0.2) {
this.acc.x = (this.vel.x < 0) ? this.friction : -this.friction;
} else {
this.vel.x = 0;
this.acc.x = 0;
}
this.vel.x += this.acc.x; // vel += acc
this.pos.x += this.vel.x; // pos += vel
}
moveY() {
//MOVE Y
if (keyInput[UP_ARROW] && this.jumps > 0 && this.canMove) {
this.jumps--;
this.vel.y = -this.jumpForce;
}
this.acc.y += this.gravity;
this.vel.y += this.acc.y;
this.pos.y += this.vel.y;
this.acc.y = 0; // Reset acceleration
if (this.pos.y >= height - this.height) {
this.pos.y = height-this.height
this.jumps = this.numJumps;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
</body>
</html>
I'm making a 2D platformer game, and all block collisions work correctly except for the left side of a horizontally moving block. Here's what the block looks like (ignore the lag):
Here's the code that makes up the moving block:
if (type.equals("moving-horizontal-2x1")) {
image(img2x1, pos.x, pos.y, 200, 100);
pos.x += movingSpeed;
if (pos.x > stop) {
movingSpeed = -movingSpeed;
}
if (pos.x < start) {
movingSpeed = abs(movingSpeed);
}
}
When the player collides with the block, it works for all sides except the left side on the X axis, as shown by the image below.
This video shows what happens when the player collides with the moving block: https://www.youtube.com/watch?v=ewVSYd5h4rg
As you can see, the player gets moved to the other side of the block. I don't know why this is happening, since the collision detection/resolution code is the same as the other static blocks. Why does only one side work?
Here is my collision detection code for the X axis:
if (rectCollide(player.pos.x, player.pos.y, player.width, player.height, pos.x, pos.y, width, height)) {
if (player.vel.x < 0) { // If the player moved left and collided with the right side of block
player.pos.x = pos.x + width;
} else { // If the player moved right and collided with the left side of block (this is the broken side)
player.pos.x = pos.x - player.width;
}
player.vel.x = 0;
}
I've tried fixing this issue by incrementing the player's x pos when it collides with the left side, by doing something like player.pos.x += movingSpeed, but this still doesn't work.
I believe the bug has something to do with how I draw the moving block, since the collision detection/resolution code works perfectly fine with all other static blocks.
Thanks for any help!
The problem occurs when you are slowly moving away from the block, but the block is faster than you. The player's direction of movement therefore says nothing about whether he is to the left or to the right of the obstacle. Don't check the player's velocity, check the player's position relative to the obstacles position:
Replace
if (player.vel.x < 0)
with
if (player.pos.x > this.x)

how to define a color for an instance of a class in Java Scipt

I've making a breakout game and I had to make some blocks and give them random colors defined in a array, but for making more blocks I had to use a for loop. So, when I add them to my update function, colors are flashing at frame rate. I think you'll understand better if you run the snippet
one more thing: that canvasRendering...rundedRectangle is a function that draws rounded edge rectangles someone please find a solution!
CanvasRenderingContext2D.prototype.roundedRectangle = function(x, y, width, height, rounded) {
const radiansInCircle = 2 * Math.PI;
const halfRadians = (2 * Math.PI)/2;
const quarterRadians = (2 * Math.PI)/4 ;
// top left arc
this.arc(rounded + x, rounded + y, rounded, -quarterRadians, halfRadians, true);
// line from top left to bottom left
this.lineTo(x, y + height - rounded);
// bottom left arc
this.arc(rounded + x, height - rounded + y, rounded, halfRadians, quarterRadians, true) ;
// line from bottom left to bottom right
this.lineTo(x + width - rounded, y + height);
// bottom right arc
this.arc(x + width - rounded, y + height - rounded, rounded, quarterRadians, 0, true) ;
// line from bottom right to top right
this.lineTo(x + width, y + rounded) ;
// top right arc
this.arc(x + width - rounded, y + rounded, rounded, 0, -quarterRadians, true) ;
// line from top right to top left
this.lineTo(x + rounded, y) ;
};
var canvas= document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
function Player(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.show = function(){
ctx.beginPath();
ctx.rect(this.x, this.y, this.w, this.h);
ctx.fillStyle = "#ffff";
ctx.fill();
ctx.closePath();
};
this.move = function(speed){
this.x += speed;
};
}
function Ball(x,y,r){
this.x = x;
this.y = y;
this.r = r;
this.show = function(){
ctx.beginPath();
ctx.arc(this.x,this.y,this.r,0,2* Math.PI);
ctx.fillStyle = "tomato";
ctx.fill();
ctx.closePath();
};
this.move= function(speedX,speedY){
this.show();
this.speed = 2;
this.x += speedX;
this.y += speedY;
};
}
var colors = ['#A5E75A','#7254AD','#FFD606','#FF093D'];
function Block(x,y,w,h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.status =1;
this.show= function(color){
ctx.beginPath();
ctx.roundedRectangle(this.x,this.y,this.w,this.h,5);
//ctx.arc(this.x,this.y,10,0,2*Math.PI);
//ctx.fillStyle = colors[Math.floor(Math.random()*colors.length)];
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
};
}
var player = new Player(canvas.width/2-50,780,100,20);
var ball = new Ball(player.x+player.w/2, player.y,15);
var rigthPressed = false;
var leftPressed = false;
var blocks = [];
var rowCount = 5;
var columnCount = 6;
var noInRow = 6;
var blockCount = (rowCount*columnCount)+1;
var rc = {blockRow : 0,
blockCol : 0};
for(let i = 0; i < blockCount; i++){
blocks.push(new Block(rc.blockCol*60+25,rc.blockRow*60-30,50,50));
rc.blockCol++;
if(i % noInRow === 0){
rc.blockRow++;
rc.blockCol = 0;
}
}
window.addEventListener("keydown", function(e){
if(e.keyCode == 39){
rigthPressed = true;
}
if(e.keyCode == 37){
leftPressed = true;
}
});
window.addEventListener("keyup", function(e){
if(e.keyCode == 39){
rigthPressed = false;
}
if(e.keyCode == 37){
leftPressed = false;
}
});
function objMovement(){
if(rigthPressed){
player.move(5);
if (player.x > canvas.width-player.w){
player.x = canvas.width-player.w;
}
}
if(leftPressed){
player.move(-5);
if(player.x < 0){
player.x = 0;
}
}
if(ball.x > canvas.width-ball.r || ball.x < 0+ball.r){
ballSpeedX = -ballSpeedX;
}
if (/*ball.y > canvas.height-ball.r ||*/ball.y < 0+ball.r){
ballSpeedY = -ballSpeedY;
}
if(ball.x<player.x+player.w &&ball.x>player.x && ball.y>player.y && ball.y<player.y+player.h){
ballSpeedY = -ballSpeedY;
ballSpeedX= ballSpeedX;
}
function Bump(){
if (ball.x>player.x && ball.x<player.x+player.w/2){
if (ball.y >= player.y){
ballSpeedX = -5;
}
}
if(ball.x>player.x+player.w/2 && ball.x<player.x+player.w){
if(ball.y >= player.y){
ballSpeedX = 5;
}
}
}
//Bump();
}
function reload(){
if (ball.y>canvas.height){
//alert('gameOver');
ball.x =player.x+player.w/2;
ball.y = player.y-ball.r;
ballSpeedX = 0;
ballSpeedY = 0;
}
}
var ballSpeedX = 0;
var ballSpeedY = -0;
function collision(){
for(let i=1;i<blockCount;i++){
if(ball.x>blocks[i].x &&
ball.x<blocks[i].x+blocks[i].w &&
ball.y>blocks[i].y &&
ball.y<blocks[i].y+blocks[i].h){
blocks[i].status = 0;
ballSpeedY = -ballSpeedY;
blocks.splice(i,1);
blockCount--;
//ballSpeedX = 0;
//ballSpeedY = 0;
console.log('hit');
}
}
}
function update(){
ctx.clearRect(0,0,canvas.width,canvas.height);
objMovement();
for(let i=1;i<blockCount;i++){
if(blocks[i].status == 1){
blocks[i].show(colors[Math.floor(Math.random()*colors.length)]);
}
}
collision();
ball.show();
ball.move(ballSpeedX,ballSpeedY);
player.show();
reload();
window.requestAnimationFrame(update);
}
update();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🌝🌝</title>
<style>
#body{
background-color: rgb(31, 30, 30);
}
#gameCanvas{
border: 15px solid rgb(44, 44, 44);
border-radius: 20px;
background-color:rgb(19, 18, 18);
margin: 250px;
}
</style>
</head>
<body id="body">
<canvas id="gameCanvas" width=400 height=800></canvas>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Because you remove and redraw all rectangles from the canvas each update and assign a new color on show, they get assigned a new color each update. You might be able to avert this by adding a property color to the rectangle, which is initialised (once, so in the initial for loop) with a random color, and alter the show function to use this.color rather than accept a color as an argument. This way, you don't assign a new color to a rectangle each update, and it won't change color each update.

Why isnt collision detection working? (p5 js frame work)

I created a collision detection between Snake and BasicEnemy. I created a for loop to make five different enemies but the collision detection doesn't get called on any of the enemies that were created from the for loop. The collision only works with the one BasicEnemy object. Why isn't collision function being called for all of the enemies inside the array? Thank you.
Sketch.js
var snake;
var food;
var basicEnemy;
var scl = 20;
var enemies = [];
function setup() {
createCanvas(600, 500);
snake = new Snake();
basicEnemy = new BasicEnemy();
//** CREATE FIVE ENEMIES **
for (var i = 0; i < 5; i++) {
enemies[i] = new BasicEnemy();
}
}
// **FUNCTION WHEN SNAKE HITS ENEMY**
function collision() {
console.log("hit!");
}
function draw() {
background(51);
//Draw snake
snake.update();
snake.show();
//Draw basicEnemy
basicEnemy.update();
basicEnemy.show();
//** LOOP THROUGH ENEMIES AND UPDATE AND SHOW **
for (var i = 0; i < enemies.length; i++) {
enemies[i].show();
enemies[i].update();
if (enemies[i].hits(snake)) {
collision();
}
}
}
function keyPressed() {
if (keyCode === UP_ARROW){
snake.dir(0, -1);
} else if (keyCode === DOWN_ARROW) {
snake.dir(0, 1);
} else if (keyCode === LEFT_ARROW) {
snake.dir(-1 , 0);
} else if (keyCode === RIGHT_ARROW) {
snake.dir(1 , 0);
}
}
BasicEnemy.js
function BasicEnemy() {
this.x = random(700);
this.y = random(700);
this.velX = 15;
this.velY = 15;
}
//** FUNCTION TO CHECK IF ENEMY AND SNAKE ARE IN THE SAME LOCATION **
this.hits = function (pos) {
var = d = dist(this.x, this.y, pos.x, pos.y);
if(d < 1) {
return true;
} else {
return false;
}
}
this.show = function () {
fill(255, 0, 100);
rect(this.x, this.y, scl, scl);
}
Snake.js
function Snake() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;
this.update = function() {
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.show = function() {
fill(255);
rect(this.x, this.y, scl, scl);
}
this.dir = function (x , y) {
this.xspeed = x;
this.yspeed = y;
}
}
Because you're essentially checking for the distance between the top left corners of the snake and the enemy, this'll only return true, if they completely overlap.
Use an AABB collision detection instead:
return this.x + scl >= pos.x && this.x <= pos.x + scl && this.y + scl >= pos.y && this.y <= pos.y + scl;
This returns true, if the first rectangle contains the second rectangle.
MDN says:
One of the simpler forms of collision detection is between two rectangles that are axis aligned — meaning no rotation. The algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. Any gap means a collision does not exist.

Collision detection not working for canvas

I've been trying to make a game but there are obstacles. I have a (ball) player and a square (obstacle) and I can't figure out how to make a collision detection thing to work. Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<title>Ball Race</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function (x, y, radius, fillCircle) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function (x, y) {
ctx.fillRect(x, y, 20, 20)
}
var Object = function () {
this.x = width / 4;
this.y = height / 4;
}
// The Ball constructor
var Ball = function () {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 5;
this.ySpeed = 0;
};
// Update the ball's position based on its speed
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Draw the ball at its current position
Ball.prototype.draw = function () {
circle(this.x, this.y, 10, true);
};
Object.prototype.draw = function () {
drawRect(this.x, this.y)
}
//collision types
Object.prototype.checkCollision = function () {
var col1 = this.x == ball.x && this.y == ball.y;
var col2 = this.x + 1 == ball.x && this.y == ball.y;
var col3 = this.x + 2 == ball.x && this.y == ball.y;
var col4 = this.x + 3 == ball.x && this.y == ball.y;
if (col1 || col2 || col3 || col4) {
alert("COLLISION!");
}
}
// Set the ball's direction based on a string
Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -5;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 5;
} else if (direction === "left") {
this.xSpeed = -5;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 5;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var ball = new Ball();
var object = new Object();
// An object to convert keycodes into action names
var keyActions = {
32: "stop",
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
// The animation function, called every 30 ms
setInterval(function () {
ctx.clearRect(0, 0, width, height);
ball.draw();
ball.move();
object.draw();
ctx.strokeRect(0, 0, width, height);
}, 30);
setInterval(function () {
object.checkCollision();
}, 1)
</script>
</body>
</html>
How would you code this? Please give an example similar to mine.
It seems like most of the functionality is there you're just missing the correct logic in the checkCollision. I would change it to something like:
Object.prototype.checkCollision = function() {
var colx = (ball.x-ball.radius<this.x&&ball.x+ball.radius>this.x)||(ball.x-ball.radius<this.x+20&&ball.x+ball.radius>this.x+20);
var coly = (ball.y-ball.radius<this.y&&ball.y+ball.radius>this.y)||(ball.y-ball.radius<this.y+20&&ball.y+ball.radius>this.y+20);
if(colx&&coly){
console.log('collision');
}
}
colx checks the x collision, to see if the ball is in between the objects position. coly does the same thing but for the y variable. If both are true then there is a collision.
I added radius variable to Ball
var Ball = function() {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 5;
this.ySpeed = 0;
this.radius = 10;
};
Here is a fiddle

Remove object on collision with ball

I know you can fillRect right? And you can clearRect. But what happens if there's an animation and you have to remove an object although it would be redrawn from setInterval. How would you remove the fillRect?
Here's an example:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function (x, y, radius, fillCircle, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function (x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}
var Object = function (xPos, yPos) {
this.x = xPos;
this.y = yPos;
}
// The Ball constructor
var Ball = function () {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 0;
this.ySpeed = 0;
this.radius = 10;
};
// Update the ball's position based on its speed
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Draw the ball at its current position
Ball.prototype.draw = function () {
circle(this.x, this.y, 10, true, "Black");
};
Object.prototype.draw = function () {
drawRect(this.x, this.y, "Black")
}
Object.prototype.drawKey = function (color) {
drawRect(this.x, this.y, "Yellow")
}
Object.prototype.checkCollision = function (direction) {
return (ball.x-ball.radius < this.x + 20)
&& (ball.x+ball.radius > this.x)
&& (ball.y-ball.radius < this.y + 20)
&& (ball.y+ball.radius > this.y)
;
}
function draw() {
ctx.clearRect(0, 0, width, height);
ball.draw();
object1.draw("Blue");
object2.draw();
object3.draw();
object4.draw();
object5.draw();
key.drawKey();
ctx.strokeRect(0, 0, width, height);
}
function simulate() {
for (z = 0; z < 5; z++) {
var prev_ball_x = ball.x;
var prev_ball_y = ball.y;
ball.move();
// handle collision here
if (object1.checkCollision() || object2.checkCollision() || object3.checkCollision() || object4.checkCollision() || object5.checkCollision()) {
ball.setDirection('stop');
// reset ball's position so they do not overlap
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
if (key.checkCollision()) {
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
}
$("body").keyup(function (event) {
ball.setDirection('stop');
})
}
setInterval(function () {
// separate drawing and simulating phases
simulate();
draw();
}, 30);
// Set the ball's direction based on a string
Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -1;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 1;
} else if (direction === "left") {
this.xSpeed = -1;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 1;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var ball = new Ball();
var object1 = new Object(50, 0);
var object2 = new Object(50, 20);
var object3 = new Object(50, 40);
var object4 = new Object(50, 60);
var object5 = new Object(50, 80);
var key = new Object(70, 70);
// An object to convert keycodes into action names
var keyActions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>
You move around a ball with your arrow keys. When I collide with the yellow block, I want it to disappear. Using clearRect would not work simply because it would be redrawn in the setInterval. How would I make it disappear?
Generally when you have several items in a game you place them into a sort of objects array, then when you draw you loop through and call .draw() on each item. Doing it this way allows you to remove items you do not want (such as key), and as such it will no longer be drawn. In your case one thing we could do (assuming there is only a single key) is give your ball a hasKey property. And on collision set it from false to true. Then inside draw, if you wish to also remove the collisions you would do !ball.hasKey && key.checkCollision() inside your collision conditional for the key:
if(!ball.hasKey) key.drawKey();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var circle = function (x, y, radius, fillCircle, color) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fillCircle) {
ctx.fill();
} else {
ctx.stroke();
}
};
var drawRect = function (x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, 20, 20)
}
var Object = function (xPos, yPos) {
this.x = xPos;
this.y = yPos;
}
// The Ball constructor
var Ball = function () {
this.x = width / 2;
this.y = height / 2;
this.xSpeed = 0;
this.ySpeed = 0;
this.radius = 10;
this.hasKey = false;
};
// Update the ball's position based on its speed
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 11) {
this.x = 11;
} else if (this.x > width - 11) {
this.x = width - 11;
} else if (this.y < 11) {
this.y = 11;
} else if (this.y > height - 11) {
this.y = height - 11;
}
};
// Draw the ball at its current position
Ball.prototype.draw = function () {
circle(this.x, this.y, 10, true, "Black");
};
Object.prototype.draw = function () {
drawRect(this.x, this.y, "Black")
}
Object.prototype.drawKey = function (color) {
drawRect(this.x, this.y, "Yellow")
}
Object.prototype.checkCollision = function (direction) {
return (ball.x-ball.radius < this.x + 20)
&& (ball.x+ball.radius > this.x)
&& (ball.y-ball.radius < this.y + 20)
&& (ball.y+ball.radius > this.y)
;
}
function draw() {
ctx.clearRect(0, 0, width, height);
ball.draw();
object1.draw("Blue");
object2.draw();
object3.draw();
object4.draw();
object5.draw();
if(!ball.hasKey) key.drawKey();
ctx.strokeRect(0, 0, width, height);
}
function simulate() {
for (z = 0; z < 5; z++) {
var prev_ball_x = ball.x;
var prev_ball_y = ball.y;
ball.move();
// handle collision here
if (object1.checkCollision() || object2.checkCollision() || object3.checkCollision() || object4.checkCollision() || object5.checkCollision()) {
ball.setDirection('stop');
// reset ball's position so they do not overlap
ball.x = prev_ball_x;
ball.y = prev_ball_y;
}
if (!ball.hasKey && key.checkCollision()) {
ball.x = prev_ball_x;
ball.y = prev_ball_y;
ball.hasKey = true;
}
}
$("body").keyup(function (event) {
ball.setDirection('stop');
})
}
setInterval(function () {
// separate drawing and simulating phases
simulate();
draw();
}, 30);
// Set the ball's direction based on a string
Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -1;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 1;
} else if (direction === "left") {
this.xSpeed = -1;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 1;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};
// Create the ball object
var ball = new Ball();
var object1 = new Object(50, 0);
var object2 = new Object(50, 20);
var object3 = new Object(50, 40);
var object4 = new Object(50, 60);
var object5 = new Object(50, 80);
var key = new Object(70, 70);
// An object to convert keycodes into action names
var keyActions = {
37: "left",
38: "up",
39: "right",
40: "down"
};
// The keydown handler that will be called for every keypress
$("body").keydown(function (event) {
var direction = keyActions[event.keyCode];
ball.setDirection(direction);
});
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<canvas id="canvas" width="800" height="200"></canvas>

Categories

Resources