How to move an object back and forth in p5js javascript - javascript

After a few hours of work and research (I just started learning p5js and javascript) I have about 50 lines of code that creates a grid of circles and begins to move them across the canvas. Before I get into my issue, I will share the code.
var circles = [];
function setup() {
createCanvas(500, 500);
for (var a = 50; a < width - 300; a += 20) {
for (var b = 50; b < height - 300; b += 20) {
circles.push(new Circle(a, b));
}
}
}
function draw() {
background(50);
for (var b = 0; b < circles.length; b++) {
circles[b].show();
}
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.show = function() {
fill(255);
noStroke();
ellipse(this.x, this.y, 10, 10);
if (this.x < 51) {
this.x += 1
this.y += 1
}
if (this.x < 430) {
this.x += 1
this.y += 1
}
if (this.x > 430) {
this.x -= 1
this.y -= 1
}
if (this.x < 51) {
this.x += 1
this.y += 1
}
}
}
What I would like to do is move this grid of circles starting at (50,50) to the bottom right corner. Once it hits (width-50,height-50) I'd like the movement to reverse back to the starting point, and then back the other way. This code moves the circles to the bottom right corner successfully, them something goes wrong. The circles don't reverse their movement, rather, they get messed up. I thought the if statements would handle this but I must be missing something. I trouble shooted for about an hour and now I thought I'd ask SO. Thanks!

Add a moving direction to the object. Change the direction when the object goes out of bounds:
var circles = [];
function setup() {
createCanvas(500, 500);
for (var a = 50; a < width - 300; a += 20) {
for (var b = 50; b < height - 300; b += 20) {
circles.push(new Circle(a, b));
}
}
}
function draw() {
background(50);
for (var b = 0; b < circles.length; b++) {
circles[b].show();
}
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.dx = 1;
this.dy = 1
this.show = function() {
fill(255);
noStroke();
ellipse(this.x, this.y, 10, 10);
this.x += this.dx
this.y += this.dy
if (this.x < 51 || this.y < 51) {
this.dx = 1
this.dy = 1
}
if (this.x > 430 || this.y > 430) {
this.dx = -1
this.dy = -1
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
If you do not want to move the objects individually, you must use 1 direction of movement for all objects:
var circles = [];
function setup() {
createCanvas(500, 500);
for (var a = 50; a < width - 300; a += 20) {
for (var b = 50; b < height - 300; b += 20) {
circles.push(new Circle(a, b));
}
}
}
var dx = 1
var dy = 1
function draw() {
background(50);
mx = dx
my = dy
for (var b = 0; b < circles.length; b++) {
circles[b].show(mx, my);
}
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.show = function(mx, my) {
fill(255);
noStroke();
ellipse(this.x, this.y, 10, 10);
this.x += mx
this.y += my
if (this.x < 51) {
dx = 1
dy = 1
}
if (this.x > 430) {
dx = -1
dy = -1
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Related

How to push one object infront of another p5js javascript

I have been stuck on this for hours and am unsure on what to do.
Here is my code:
var circles = [];
var circles2 = [];
function setup() {
createCanvas(500, 500);
//there's a "b" for every "a"
for (var a = 50; a < width - 300; a += 20) {
for (var b = 50; b < height - 300; b += 20) {
//add the circles to the array at x = a and y = b
circles.push(new Circle(a, b));
circles2.push(new Conn(a, b));
}
}
for (var a = 250; a < width - 50; a += 20) {
for (var b = 250; b < height - 50; b += 20) {
//add the circles to the array at x = a and y = b
}
}
console.log(circles.length);
}
function draw() {
background(50);
for (var b = 0; b < circles.length; b++) {
circles2[b].show();
circles[b].show();
//console.log("shown");
}
for (var b = 0; b < circles2.length; b++) {
//circles2[b].show();
//console.log("shown");
}
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.show = function() {
fill(255);
noStroke();
ellipse(this.x, this.y, 10, 10);
//console.log("showing");
push();
fill(255);
noStroke();
translate(250, 250);
ellipse(this.x, this.y, 10, 10);
pop();
}
}
function Conn(x, y) {
this.x = x;
this.y = y;
this.show = function() {
noStroke();
let h = 0;
for (let i = 0; i < 251; i++) {
fill(h, 90, 120);
h = (h + 1) % 500;
noStroke();
push()
ellipse(this.x + i, this.y + i, 10, 10);
noStroke();
noLoop();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
It generates a grid of squares that is supposed to connect to a different grid of squares through gradient lines. However, only the bottom row and right most column of circles on the bottom right circle grid show up for some reason. How can I make it that all circles on the bottom right circle grid are in front of the gradient lines? I've tried push, pop, and everything else. I'm really confused as to why only some of the circles are showing up, but the others are stuck behind these gradients.
Unless you use p5.js in WEBGL mode then there is no object stacking order or z-index or z-buffer. Shapes that you draw always overlap whatever was drawn before them. So in order to make a shape appear on top of another you need to draw the shape underneath first, followed by the shape on top. I believe I was able to achieve this by rearranging your code a little:
var circles = [];
var connections = [];
function setup() {
createCanvas(500, 500);
//there's a "b" for every "a"
for (var a = 50; a < width - 300; a += 20) {
for (var b = 50; b < height - 300; b += 20) {
//add the circles to the array at x = a and y = b
circles.push(new Circle(a, b));
connections.push(new Conn(a, b));
}
}
for (var a = 250; a < width - 50; a += 20) {
for (var b = 250; b < height - 50; b += 20) {
//add the circles to the array at x = a and y = b
}
}
console.log(circles.length);
}
function draw() {
background(50);
// Show connections first
for (var b = 0; b < connections.length; b++) {
connections[b].show();
}
// Show circles second so that they appear on top of the connections
for (var b = 0; b < circles.length; b++) {
circles[b].show();
}
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.show = function() {
fill(255);
noStroke();
ellipse(this.x, this.y, 10, 10);
//console.log("showing");
push();
fill(255);
noStroke();
translate(250, 250);
ellipse(this.x, this.y, 10, 10);
pop();
}
}
function Conn(x, y) {
this.x = x;
this.y = y;
this.show = function() {
noStroke();
let h = 0;
for (let i = 0; i < 251; i++) {
fill(h, 90, 120);
h = (h + 1) % 500;
noStroke();
push()
ellipse(this.x + i, this.y + i, 10, 10);
noStroke();
noLoop();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

Land a character on a block after he jumps on it in p5.js game

I'm just trying to create a small 2d game where we control a character that can place block on the "map" with the mouse and jump on it to climb etc. It's just a test to practice.
I've achieved to make the character stops when he walk into blocks.
But, i'm facing a problem when I want my character to jump on a block, i'm not able to make him land on it. I can't find the condition to.
Can someone helps me on it ? The code that handle the collision between the character and blocks is in the draw function and in the for.
Controls
Left: Q
Right: D
Jump: Space Bar
Place a block: Mouse Click
Remove a block: Mouse Click
Edit: You might have ask yourself why i'm using some variables that are not declared anywhere. It's because they are given by P5.js. (ex: width)
function Man() {
this.w = 20;
this.h = 40;
this.x = width/2;
this.y = height - this.h;
this.canJump = true;
this.velocity = 0;
this.show = function(){
fill(255);
rect(this.x, this.y, this.w, this.h);
}
this.update = function(){
this.velocity += gravity;
this.y += this.velocity;
if(this.y + this.h > height) {
this.y = height - this.h ;
this.velocity = 0;
this.canJump = true;
}
if(this.x <= 0) {
this.x = 0;
}
if(this.x + this.w >= width) {
this.x = width - this.w;
}
}
this.jump = function(){
if(this.canJump) {
man.velocity -= 6;
this.canJump = false;
}
}
}
var man;
var ground;
var gravity = 0.4;
function setup(){
frameRate(60);
createCanvas(640, 480);
man = new Man();
}
var tilesSize = 20;
var tiles = [];
for(var i = 0; i < 640; i+= tilesSize) {
for(var j = 0; j < 480; j+= tilesSize) {
tiles.push({x:i, y:j, empty: true});
}
}
function draw(){
background(0);
noStroke();
push();
for(var i = 0; i < tiles.length; i++) {
if(!tiles[i].empty) {
fill(150);
rect(tiles[i].x, tiles[i].y, tilesSize, tilesSize);
}
if(mouseX >= tiles[i].x && mouseX < tiles[i].x + tilesSize && mouseY >= tiles[i].y && mouseY < tiles[i].y + tilesSize) {
if(tiles[i].empty) {
fill(50);
rect(tiles[i].x, tiles[i].y, tilesSize, tilesSize);
}else {
fill(255,0,0);
rect(tiles[i].x, tiles[i].y, tilesSize, tilesSize);
}
}
// HERE IS CONDITIONS FOR COLLISION WITH BLOCK
if(!tiles[i].empty) {
if(tiles[i].x + tilesSize >= man.x && tiles[i].x < man.x && tiles[i].y < man.y + man.h ) {
man.x = tiles[i].x + tilesSize;
}
if(man.x + man.w >= tiles[i].x && man.x <= tiles[i].x && tiles[i].y < man.y + man.h) {
man.x = tiles[i].x - man.w;
}
}
}
pop();
man.show();
man.update();
moveMan();
}
function moveMan(){
if(keyIsDown(81)) {
man.x -= 2;
}
if(keyIsDown(68)) {
man.x += 2;
}
}
function keyPressed() {
if(keyIsDown(32)) {
man.jump();
}
}
function mouseClicked() {
for(var i = 0; i < tiles.length; i++) {
if(mouseX >= tiles[i].x && mouseX < tiles[i].x + tilesSize && mouseY >= tiles[i].y && mouseY < tiles[i].y + tilesSize) {
if(tiles[i].empty) {
tiles[i].empty = false;
}else {
tiles[i].empty = true;
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>

how can I detect collision in a 2D tile game map

I made this basic game where I drew a map and a player, the player can move anywhere but how can I make so that it wont move when its on the tile[1] in the map?
also when I try to check if the player.x is greater than 50 it could go left it works but than if I click 2 keys at once it goes through
const context = document.querySelector("canvas").getContext("2d");
var rgb = 'rgb(' + Math.random()*256 + ',' + Math.random()*256 + ',' + Math.random()*256 + ','+Math.random() + ')';
document.onload = Loop();
var width = 1500;
var height = 800;
function Loop(){
var width = 1500;
var height = 800;
context.canvas.height = height;
context.canvas.width = width;
this.interval = setInterval(Update, 1000/100);
}
const Player = function(x, y, w, h, color) {
this.x = x; this.y = y; this.w = w; this.h = h;
this.speedY = 0; this.speedX = 0;
this.Draw = function(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.w, this.h);
};
this.Move = function(){
this.x += this.speedX;
this.y += this.speedY;
};
};<code>
var player = new Player(100,100,50, 50, rgb);
var Key = {};
function Update(){
context.clearRect(0, 0, width, height);
Map();
player.Draw();
player.Move();
onkeydown = onkeyup = function(e){
player.speedX = 0;
player.speedY = 0;
e = e || event;
Key[e.keyCode] = e.type == 'keydown';
if(Key[37] || Key[65]) {player.speedX -= 2}
if(Key[38] || Key[87]) {player.speedY -= 2}
if(Key[39] || Key[68]) {player.speedX += 2}
if(Key[40] || Key[83]) {player.speedY += 2}
if(Key[32]) {player.color = 'rgb(' + Math.random()*256 + ',' + Math.random()*256 + ',' + Math.random()*256 + ','+Math.random()*1 + ')';}
};
}
var map = [
1, 1, 1, 1, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 0, 0, 0, 1,
1, 1, 1, 1, 1
];
var row = 5;
var column = 5;
function Map(){
for(let y = -1; y < column; y++){
for(let x = -1; x < row; x++){
switch(map[((y*row) + x)]) {
case 0: context.fillStyle = player.color;
break;
case 1: context.fillStyle = "#ffffff";
break;
default: context.fillStyle = "#000000";
}
context.fillRect(x*50, y*50, 50, 50);
}
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
script {
display: none;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
void function() {
"use strict";
// Classes
function Camera(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
}
Camera.prototype = {
set: function(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
},
pan: function(x,y) {
this.x += x || 0.0;
this.y += y || 0.0;
}
};
var nextID = 0;
function Tile(colour) {
this.id = nextID++;
this.colour = colour || "black";
}
function Map(width,height) {
this.width = width || 1;
this.height = height || 1;
this.map = [];
this.map.length = this.height;
for (var y = 0; y < this.height; ++y) {
this.map[y] = [];
this.map[y].length = width;
for (var x = 0; x < this.width; ++x) {
this.map[y][x] = Math.random() < 0.2 ?
this.TILE_WALL:
this.TILE_GRASS;
}
this.map[y][0] = this.TILE_WALL;
this.map[y][this.width - 1] = this.TILE_WALL;
}
for (var x = 0; x < this.width; ++x) {
this.map[0][x] = this.TILE_WALL;
this.map[this.height - 1][x] = this.TILE_WALL;
}
}
Map.prototype = {
TILE_WIDTH: 32.0,
TILE_HEIGHT: 32.0,
INV_TILE_WIDTH: 0.0,
INV_TILE_HEIGHT: 0.0,
TILE_AIR: new Tile("#00000000"),
TILE_GRASS: new Tile("#00AA00FF"),
TILE_WALL: new Tile("#555555FF"),
set: function(x,y,tile) {
this.map[y][x] = tile;
},
scaleX: function(x) {
return (x * this.INV_TILE_WIDTH) | 0;
},
scaleY: function(y) {
return (y * this.INV_TILE_HEIGHT) | 0;
},
isColliding: function(x,y) {
return x > -1 && x < this.width
&& y > -1 && y < this.height
&& this.map[y][x].id > 1;
},
render: function(ctx,camera) {
for (var y = 0; y < this.height; ++y) {
for (var x = 0; x < this.width; ++x) {
var tile = this.map[y][x];
var _x = x * this.TILE_WIDTH - camera.x;
var _y = y * this.TILE_HEIGHT - camera.y;
ctx.fillStyle = tile.colour;
ctx.fillRect(_x,_y,this.TILE_WIDTH - 1,this.TILE_HEIGHT - 1);
}
}
}
};
Map.prototype.INV_TILE_WIDTH = 1.0 / Map.prototype.TILE_WIDTH;
Map.prototype.INV_TILE_HEIGHT = 1.0 / Map.prototype.TILE_HEIGHT;
function Player(x,y) {
this.x = x || 0.0;
this.y = y || 0.0;
this.dx = 0.0;
this.dy = 0.0;
this.isUp = false;
this.isDown = false;
this.isLeft = false;
this.isRight = false;
}
Player.prototype = {
WIDTH: 20.0,
HEIGHT: 20.0,
ACCELERATION: 1.0,
DEACCELERATION: 0.5,
MAX_SPEED: 3.0,
tick: function(map) {
// Movement
if (this.isUp) {
this.dy -= this.ACCELERATION;
if (this.dy < -this.MAX_SPEED) {
this.dy = -this.MAX_SPEED;
}
} else if (this.dy < 0.0) {
this.dy += this.DEACCELERATION;
if (this.dy > 0.0) {
this.dy = 0.0;
}
}
if (this.isDown) {
this.dy += this.ACCELERATION;
if (this.dy > this.MAX_SPEED) {
this.dy = this.MAX_SPEED;
}
} else if (this.dy > 0.0) {
this.dy -= this.DEACCELERATION;
if (this.dy < 0.0) {
this.dy = 0.0;
}
}
if (this.isLeft) {
this.dx -= this.ACCELERATION;
if (this.dx < -this.MAX_SPEED) {
this.dx = -this.MAX_SPEED;
}
} else if (this.dx < 0.0) {
this.dx += this.DEACCELERATION;
if (this.dx > 0.0) {
this.dx = 0.0;
}
}
if (this.isRight) {
this.dx += this.ACCELERATION;
if (this.dx > this.MAX_SPEED) {
this.dx = this.MAX_SPEED;
}
} else if (this.dx > 0.0) {
this.dx -= this.DEACCELERATION;
if (this.dx < 0.0) {
this.dx = 0.0;
}
}
// Collision
if (this.dx !== 0.0) {
var minY = map.scaleY(this.y);
var maxY = map.scaleY(this.y + this.HEIGHT);
var minX = 0;
var maxX = 0;
if (this.dx < 0.0) {
minX = map.scaleX(this.x + this.dx);
maxX = map.scaleX(this.x);
} else {
minX = map.scaleX(this.x + this.WIDTH);
maxX = map.scaleX(this.x + this.WIDTH + this.dx);
}
loop:
for (var y = minY; y <= maxY; ++y) {
for (var x = minX; x <= maxX; ++x) {
if (map.isColliding(x,y)) {
this.x = this.dx < 0.0 ?
(x + 1) * map.TILE_WIDTH:
x * map.TILE_WIDTH - this.WIDTH - 1;
this.dx = 0.0;
break loop;
}
}
}
}
if (this.dy !== 0.0) {
var minX = map.scaleX(this.x);
var maxX = map.scaleX(this.x + this.WIDTH);
var minY = 0;
var maxY = 0;
if (this.dy < 0.0) {
minY = map.scaleY(this.y + this.dy);
maxY = map.scaleY(this.y);
} else {
minY = map.scaleY(this.y + this.HEIGHT);
maxY = map.scaleY(this.y + this.HEIGHT + this.dy);
}
loop:
for (var y = minY; y <= maxY; ++y) {
for (var x = minX; x <= maxX; ++x) {
if (map.isColliding(x,y)) {
this.y = this.dy < 0.0 ?
(y + 1) * map.TILE_HEIGHT:
y * map.TILE_HEIGHT - this.HEIGHT - 1;
this.dy = 0.0;
break loop;
}
}
}
}
this.x += this.dx;
this.y += this.dy;
},
render: function(ctx,camera) {
camera.set(this.x,this.y);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.fillStyle = "darkred";
ctx.beginPath();
ctx.rect(this.x - camera.x,this.y - camera.y,this.WIDTH,this.HEIGHT);
ctx.fill();
ctx.stroke();
}
};
// Variables
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var camera = null;
var map = null;
var player = null;
// Functions
function onKeyDown(e) {
switch(e.key.toUpperCase()) {
case "W": player.isUp = true; break;
case "S": player.isDown = true; break;
case "A": player.isLeft = true; break;
case "D": player.isRight = true; break;
}
}
function onKeyUp(e) {
switch(e.key.toUpperCase()) {
case "W": player.isUp = false; break;
case "S": player.isDown = false; break;
case "A": player.isLeft = false; break;
case "D": player.isRight = false; break;
}
}
function loop() {
// Tick
player.tick(map);
// Render
ctx.fillStyle = "gray";
ctx.fillRect(-canvasWidth >> 1,-canvasHeight >> 1,canvasWidth,canvasHeight);
map.render(ctx,camera);
player.render(ctx,camera);
//
requestAnimationFrame(loop);
}
// Entry point (first to execute)
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
ctx.translate(canvasWidth >> 1,canvasHeight >> 1);
camera = new Camera(0.0,0.0);
map = new Map(10,10);
player = new Player(40.0,40.0);
map.set(1,1,map.TILE_GRASS);
addEventListener("keydown",onKeyDown);
addEventListener("keyup",onKeyUp);
loop();
}
}();
</script>
</body>
</html>
Firstly, looking at your code, there are some things that are missing which is required to implement basic collision detection and those are:
The player's current direction that he/she is moving in. This is important because it allows the function determining the collision detection to distinguish which side it is checking for the collision (Up, down, left, or right) since a player can only collide with one side at a time.
The tile's position and size. This is also very important because like the first point, there is only one side of the tile that the player can collide with and knowing the size and position can determine if it is a collision or not based on the players size and position.
Also, since you mentioned it is a basic game, the implementation below is a basic collision detection. If you were to make a more complex and bigger game, you should try looking into quad trees for more efficient collision detection:
https://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374
Now this is the function for detecting collision, for the sake of readability and shortness, p will represent the player object and t would represent the tile object. This function returns whether or not the player is colliding with a tile based on their direction of movement.
function isColliding(p, t){
if (p.direction == 'up') {
return p.y +(p.height/2)-p.speedY< t.y + t.height && p.y > t.y
&& p.x + p.width > t.x && p.x < t.x + t.width;
}
if (p.direction == 'down') {
return p.y + (p.height/2)+p.speedY > t.y && p.y < t.y
&& p.x + p.width > t.x && p.x < t.x + t.width;
}
if (p.direction == 'right') {
return p.x + p.width+p.speedX > t.x && p.x < t.x
&& p.y +(p.height/2)> t.y && p.y + p.height < t.y +t.height+ (p.height / 2);
}
if (p.direction == 'left') {
return p.x -p.speedX< t.x + t.width && p.x > t.x
&& p.y +(p.height/2)> t.y && p.y + p.height < t.y +t.height+ (p.height / 2);
}
return false;
}
You would probably want to put this in the player move function to constantly detect for tiles as it is moving. To do that, you'd want to modify your keydown detection so that with each different keydown, it would update the player's direction, here's a simple example:
document.onkeydown = function(event){
if (event.keyCode == 87)
player.up = true;
else if (event.keyCode == 65)
player.left = true;
else if (event.keyCode == 83)
player.down = true;
else if (event.keyCode == 68)
player.right = true;
}
and another simple example for every time the player moves (user presses a keydown):
const Player= function(/*Param stuff*/){
/*Property stuff*/
//tileArray is the array (or object, your choice) of all the current tiles in the map
this.move=function(tileArray){
//Go through all tiles to see if player is colliding with any of them
for(var t in tileArray){
if(this.up){
if(isColliding(this, tileArray[t]){
//functionality for when player collides
}else{
//functionality for when player doesn't collide
}
}
//check if player is going down, left, etc
}
}
}
These are just examples of how to implement the detection. You should use it as a reference to implement it relatively to how your code function because I didn't write it based on what you posted.
PS.
Make sure to also convert the directions to false after the user stops pressing the key.

JavaScript Brick Breaker, Bricks in array aren't being spliced?

I'm having trouble with how I remove bricks. The bricks are part of an array, and the ball continuously runs a for loop checking to see if it's hit any bricks. If it does, it splices that brick from the array. But the bricks don't disappear!
//Helper Functions
function AABBIntersect(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
}
var ball = {
//A few of the basic variables called by the upcoming function
update: function() {
this.x += this.vel.x;
this.y += this.vel.y;
if (0 > this.y) {
var offset = 0 - this.y;
this.y += 2*offset;
this.vel.y *= -1;
}
if (this.y+this.height > HEIGHT) {
this.serve();
}
if (0 > this.x || this.x+this.size > WIDTH) {
var offset = this.vel.x < 0 ? 0 - this.x : WIDTH - (this.x+this.size);
this.x += 2*offset;
this.vel.x *= -1;
}
if (AABBIntersect(this.x, this.y, this.size, this.size, player.x, player.y, player.width, player.height)) {
var offset = player.y - (this.y+this.size);
this.y += 2*offset;
var n = (this.x+this.size - player.x)/(player.width+this.size);
var phi = 0.25*pi*(2*n - 1);
var smash = Math.abs(phi) > 0.2*pi ? 1.5 : 1;
this.vel.x = smash*this.speed*Math.sin(phi);
this.vel.y = smash*-1*this.speed*Math.cos(phi);
}
for (var i = 0; i < bricks.length; i++) {
var b = bricks[i];
if (AABBIntersect(this.x, this.y, this.width, this.height, b.x, b.y, b.width, b.height)) {
bricks.splice(i, 1);
i--;
bricks.length--;
continue;
}
}
}
}
var bricks = [];
function main() {
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
} );
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
var cols = WIDTH / 40;
player.x = (WIDTH - player.width) / 2;
player.y = HEIGHT - (player.height * 2);
ball.x = (WIDTH - ball.size) / 2;
ball.y = player.y - ball.size;
ball.width = ball.size;
ball.height = ball.size;
ball.serve();
for (var i = 0; i < 7; i++) {
for (var j = 0; j < cols; j++) {
bricks.push({
color: "#f00",
x: 2 + j*40,
y: 2 + i*20,
w: 36,
h: 16
});
}
}
}
function update() {
frames++;
player.update();
ball.update();
}
function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
player.draw();
ball.draw();
for (var i = 0; i < bricks.length; i++) {
ctx.fillStyle = bricks[i].color;
ctx.fillRect(bricks[i].x, bricks[i].y, bricks[i].w, bricks[i].h);
}
ctx.restore();
}
main();
A few issues:
The brick objects do not have width or height properties, but w and h;
The splice should not happen on a brick element (b), but on the array of bricks (bricks);
The length of bricks should not be decremented after the splice, as that operation already reduces the length.
So use this loop:
for (var i = 0; i < bricks.length; i++) {
var b = bricks[i];
if (AABBIntersect(this.x, this.y, this.width, this.height, b.x, b.y, b.w, b.h)) {
bricks.splice(i, 1);
i--;
}
}

unexpected behavior during a rotation animation on canvas

I've been working on some studies with animation and with the help of some jquery I've created an animation where when a square that is moved by the users mouse through a mousemove jquery event collides with another square on the screen (square2) thats been hit will move a certain length and if the hitbox is struck near its edges than the object is expected to rotate. The problem ive been running into is that when the object rotates it creates a pseudo afterimage of the outline of the square. At first I thought that I could remove the afterImage by using a clearRect() method to encompass a larger area around square2, but doing this not only leaves my problem unresolved, but also makes a part of my first square invisible which is undesired. If anybody could hep me figure out where ive gone wrong in this code, would definitely appreciate it fellas.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 1000;
canvas.height = 400;
var width = canvas.width;
var height = canvas.height;
var particles = [];
var mouseSize = 50;
var isColliding = false;
var mouseX;
var mouseY;
var animationForward = false;
function particle() {
var particle = {
originX: width / 2,
originY: height / 2,
x: width / 2,
y: height / 2,
size: 30,
centerPointX: this.x + this.size / 2,
centerPointY: this.y + this.size / 2,
decay: .98,
vx: 0,
vy: 0,
rotate: 0,
vr: 0,
draw: function() {
ctx.fillStyle = "white";
ctx.fillRect(this.x, this.y, this.size, this.size)
// rotation logic
// method found at http://stackoverflow.com/questions/2677671/how-do-i-rotate-a-single-object-on-an-html-5-canvas
function drawImageRot(x, y, width, height, deg) {
ctx.clearRect(x, y, width, height);
//Convert degrees to radian
var rad = deg * Math.PI / 180;
//Set the origin to the center of the image
ctx.translate(x + width / 2, y + height / 2);
//Rotate the canvas around the origin
ctx.rotate(rad);
//draw the image
ctx.fillRect(width / 2 * (-1), height / 2 * (-1), width, height);
//reset the canvas
ctx.rotate(rad * (-1));
ctx.translate((x + width / 2) * (-1), (y + height / 2) * (-1));
}
//check for collision
if (mouseX < particles[0].x + particles[0].size &&
mouseX + mouseSize > particles[0].x &&
mouseY < particles[0].y + particles[0].size &&
mouseSize + mouseY > particles[0].y) {
isColliding = true;
} else {
isColliding = false;
}
//controlling velocity dependending on location of collision.
if (isColliding) {
//x axis
animationForward = true;
// checking below to see if mouseRect is hitting near the center of particleRect.
// if it hits near center the vy or vx will not be as high depending on direction and if it //does not than we will make square rotate
if (mouseX < this.x) {
this.vr = 3 + Math.random() * 10
if (mouseX + mouseSize / 2 > this.x) {
this.vx = 0 + Math.random() * 2;
} else {
this.vx = 3 + Math.random() * 3;
}
} else {
this.vr = -3 - Math.random() * 10
if (mouseX + mouseSize / 2 < this.x + this.size) {
this.vx = 0 - Math.random() * 2;
} else {
this.vx = -3 - Math.random() * 3;
}
}
//y axis checking
if (mouseY < this.y) {
if (mouseY + mouseSize / 2 > this.y) {
this.vy = 0 + Math.random() * 2;
} else {
this.vy = 3 + Math.random() * 3;
}
} else {
if (mouseY + mouseSize / 2 < this.y + this.size) {
this.vy = 0 - Math.random() * 2;
} else {
this.vy = -3 - Math.random() * 3;
}
}
}
//decay all motions each frame while animation is forward
if (animationForward) {
this.vx *= this.decay;
this.vy *= this.decay;
this.vr *= this.decay;
}
//when animation is done, set all velocities to 0
if (this.x != this.originX && Math.abs(this.vx) < .1 && this.y != this.originY && Math.abs(this.vy) < .1) {
animationForward = false;
this.vx = 0;
this.vy = 0;
this.vr = 0
}
//x check to see if animation over. if it is slowly put square back to original location
if (this.x != this.originX && !animationForward) {
if (this.x > this.originX) {
this.vx = -1;
}
if (this.x < this.originX) {
this.vx = 1;
}
if (this.x > this.originX && this.x - this.originX < 1) {
this.vx = 0;
this.x = this.originX;
}
if (this.x < this.originX && this.originX - this.x < 1) {
this.vx = 0;
this.x = this.originX;
}
}
// end x collison
// y check to see if animation over
if (this.y != this.originX && !animationForward) {
if (this.y > this.originY) {
this.vy = -1;
}
if (this.y < this.originY) {
this.vy = 1;
}
if (this.y > this.originY && this.y - this.originY < 1) {
this.vy = 0;
this.y = this.originY;
}
if (this.y < this.originY && this.originY - this.y < 1) {
this.vy = 0;
this.y = this.originY;
}
}
// end y collison
//check rotation
if (this.rotate != 0 && !animationForward) {
this.rotate = Math.round(this.rotate);
if (this.rotate < 0) {
if (this.rotate < -300) {
this.rotate += 10
} else if (this.rotate < -200) {
this.rotate += 7
} else if (this.rotate < -125) {
this.rotate += 5
} else if (this.rotate < -50) {
this.rotate += 3
} else {
this.rotate++;
}
} else {
if (this.rotate > 300) {
this.rotate -= 10;
} else if (this.rotate > 200) {
this.rotate -= 7
} else if (this.rotate > 125) {
this.rotate -= 5
} else if (this.rotate > 50) {
this.rotate -= 3
} else {
this.rotate--;
}
}
}
// move the rect based off of previous set conditions and make square rotate if edges hit
this.x += this.vx;
this.y += this.vy;
this.rotate += this.vr;
drawImageRot(this.x, this.y, this.size, this.size, this.rotate);
// boundary control
if (this.x + this.size > width || this.x < 0) {
this.vx = -this.vx * 2
}
if (this.y + this.size > height || this.y < 0) {
this.vy = -this.vy * 2
}
}
}
return particle;
}
function createParticles() {
particles.push(particle())
//wouldnt be too hard to put more particles. would have to go back and change the isColliding and animationForward global variable and make each object have their own to check. also would have to go back and implement for loops wherever i mention an element in my array
}
createParticles();
function draw() {
console.log(particles[0].rotate);
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = 'white';
ctx.fillRect(mouseX, mouseY, mouseSize, mouseSize);
particles[0].draw();
requestAnimationFrame(draw);
}
$("#canvas").mousemove(function(event) {
mouseX = event.pageX;
mouseY = event.pageY;
})
window.onload = draw();
I think your problem is right here:
draw: function() {
ctx.fillStyle = "white";
ctx.fillRect(this.x, this.y, this.size, this.size)
....
You are drawing 2nd shape here. Comment this lines and pseudo image should be gone.

Categories

Resources