I'm viewing this code for two days now and it really doesn't seem to me like anything is wrong at all. Tried changing the code in many ways but had little to no success with the lag issue of the ball. something clearly is wrong because the ball has this weird lag (sometimes it behaves normally but most of the times it has this odd lag that is causing changes in speed of the ball.)
This are two of the main functions that make the ball move and both seem OK to me.
function ball(){ //gets called 1000 times per second
if(lifeCount==0){
ctx.clearRect(0,0,900,600);
ctx.drawImage(youLose,0,0,900,600);
return;
}
else{
ctx.beginPath();
ctx.clearRect(xBall-(r+1),yBall-(r+1),2*r+2,2*r+2);
ballCollision(); //function
ctx.arc(xBall,yBall,r,0,2*Math.PI, true);
ctx.fillStyle = "#c82124";
ctx.fill();
ctx.stroke();
bricksHit(); //function (no lag)
bricksDraw(); //function (no lag)
ballPowerUp(); //function (no lag)
}
}
function ballCollision(){
if(startDirection === 1) //random start, ball begins moving "left"
xBall += -xSpeed;
if(startDirection === 2) //random start, ball begins moving "right"
xBall += xSpeed;
if(xBall>=canvas.width-r) //right wall collision
xSpeed = -xSpeed
if(xBall<=0+r) //left wall collision
xSpeed = -xSpeed
if(yBall<=0+r)//top wall collision
ySpeed = -ySpeed;
if(xBall>=x-(paddleW/2) && xBall<=x+(paddleW/2) && (yBall <= canvas.height-paddleH-r && yBall >= canvas.height-paddleH-r-4)) //bottom paddle collision
ySpeed = -ySpeed;
yBall += ySpeed;
if(yBall>=canvas.height-r){
lifeCount--;
if(lifeCount>0)
initBall(); //another chance if you still have lives left
}
}
canvas.onmousemove = function() {
if(lifeCount==0){
return;
}
else{
padd();
}
}
There is probably some rookie mistake made in the code somewhere that I just can't seem to find or I don't know what else may be causing this. If any of you has any suggestions please let me know.
also if anyone would like to see how the game actually "lags" here's a link of html file: https://drive.google.com/open?id=1A1H1MiKpIutj9Z4kdrDunHZHHYeWNfl3
Thanks in advance!
Related
just trying to make a simple pong game in p5.js. I have very recently gotten into JavaScript and can't manage to figure out collision detection between the ball and the bat. I have tried a few ways of doing it but it mostly just stopped my code from running.. etc.. would love any help!
Here is my source code:
function setup() {
createCanvas(750, 750);
}
var x = 50;
var y = 50;
var direction = 5;
var arrow = 0;
var ball;
var bat;
function draw() {
background(220);
fill ('white');
ball = ellipse (x, y, 50, 50);
x = x + direction;
if (x > width - 25){
direction = -5;
}
if (x < 25) {
direction = 5;
}
x++;
y++;
if (keyIsDown(RIGHT_ARROW)){
arrow += 7;
}
if (keyIsDown(LEFT_ARROW)){
arrow += -7;
}
fill ('black');
bat = rect(arrow, 600, 150, 15);
}
Your question is pretty broad, but basically what you want to do is imagine a "bounding rectangle" around the ball, and then use rectangle-rectangle collision to check whether the ball is colliding with a paddle. If it is, "bounce" the ball by multiplying its horizontal speed by -1.
I wrote a tutorial on collision detection available here, but the basic if statement looks like this:
if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
You also might want to read the Collision Detection with Moving Objects section of that tutorial. It's written for Processing, but everything applies to P5.js as well.
If you're having trouble getting it working, then please start over with a more basic sketch that just shows two hard-coded rectangles. Make them turn red when they're not colliding. Then work your way up from there. It's hard to answer general "how do I do this" type questions, so you'll have much better luck if you post a specific "I tried X, expected Y, but got Z instead" type question. Good luck.
All I need is to have this object travel left and right across the top of the canvas. Currently it spawns and travels right absolutely fine, then stops once it reaches the right edge of the canvas.
//mainEnemy Variables
var mainEnemy_x = 10;
var mainEnemy_y = 10;
var mainEnemyHeight = 50;
var mainEnemyWidth = 25;
var mainEnemyRight = true;
var mainEnemyLeft = false;
var mainEnemy_dx = 2;
//Drawing the Main Enemy
function drawMainEnemy()
{
ctx.beginPath();
ctx.rect(mainEnemy_x, mainEnemy_y, mainEnemyHeight, mainEnemyWidth);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();
}
//Movement speed of mainEnemy
if(mainEnemyRight && mainEnemy_x < canvas.width-mainEnemyWidth)
{
mainEnemy_x += 5;
}
else if(mainEnemyLeft && mainEnemy_x > 0)
{
mainEnemy_x -= 5;
}
//mainEnemy moves across the top of the canvas
if(mainEnemy_x + mainEnemy_dx - mainEnemyWidth > canvas.width)
{
mainEnemy_dx = -mainEnemy_dx;
}
ball_x += dx;
ball_y += dy;
mainEnemy_x += mainEnemy_dx;
}
This is all the code relevant to the object I need help with. I've tried just reversing it's x movement, with the mainEnemy_dx = -mainEnemy_dx; line, but this isn't working. I can see this code is an absolute mess at the moment, I just need to get it working then time for some serious cleanup.
Any and all help would be greatly appreciated!
First of all, you have two movement systems. One with the left and right flags and constants added or subtracted from x and the other with dx. You should just use one or the other, the latter being simpler.
For the jitter, you have to either also check that the current dx is positive when going over the right by border (and negative on left) and then switch the sign, or move the object left when a collision with right border is found.
At the moment you are moving the object 7 units right every time, then when border is found only dx is used (2 or -2) but since your object can be over the border it might vibrate between 2 and -2 always. But at least the right branch will always try to move 5 units right even when dx is negative.
Using a debugger to step through the code and inspecting the variables and branches taken while vibrating on the right edge will show exactly how it behaves.
Im currently working on getting my player sprite to move around my screen, but when a key is pressed all the sprite seems to do is disappear! I have no errors coming up in firebug, so i am assuming that the sprite isn't being redrawn correctly or something along those lines.
Here is my code for my player:
function Player()
{
var sprite = new Sprite(),
player,
x,
y,
w = sprite.width,
h = sprite.height,
speed = 4;
this.init_Player = function(pos_X, pos_Y){
player = sprite.load("player");
x = pos_X;
y = pos_Y;
};
this.update = function(delta) {
var calculated_speed = (speed * delta) * (60/1000);
$(document).keydown(function(e)
{
var cancel_default = (e.which === 32 || (e.which > 36 && e.which < 41));
cancel_default && e.preventDefault();
if(e.keyCode == 37){
x -=calculated_speed;
}
else if(e.keyCode == 38){
y -=calculated_speed;
}
else if(e.keyCode == 39){
x +=calculated_speed;
}
else if(e.keyCode == 40){
y +=calculated_speed;
}
});
};
this.draw = function() {
ctx.drawImage(player,x, y, w ,h);
};
}
The player is created in my main game javascript file like so:
player.init_Player(location_X,location_Y);
And then in my main game loop i have the now, delta and last times being made as well as the call to player.update and player.render like so:
function update(){
now = Date.now();
delta = now - last_update;
ctx.clearRect(0,0,canvas.width,canvas.height);
gameGUI.update();
player.update(delta);
player.draw();
last_update = now;
setTimeout(update,1);
}
Like i said at the top, all my sprite does on a key press is disappear. The code you can see above is all the code i have for the player so somewhere in here is the bug!
How would i accomplish making my sprite move on screen with a time-based animation like the one i've set up?
Thanks
EDIT
Also to let you know, i have last_update equal to Date.now() the line before my update call gets made initially like so:
function game_init(state) {
game_settings(state);
last_update = Date.now();
update();
}
Edit 2
On continued inspection, it doesn't seem like the sprite is disappearing after all, just moving very far e.i off the game screen... so another guess is that my calculations are wrong somewhere?
All sorted guys, i have my character moving using this little tutorial! Real easy to read and understand for the beginners out there.
LINK
What do the pros think of this tutorial?
For my education I have to make a basic game in HTML5 canvas. The game is a shooter game. When you can move left -> right and space is shoot. When I shoot the bullets will move up. The enemy moves down. When the bullet hits the enemy the enemy has to dissapear and it will gain +1 score. But the enemy will dissapear after it comes up the screen.
Demo: http://jordikroon.nl/test.html
space = shoot + enemy shows up
This is my code:
for (i=0;i<enemyX.length;i++) {
if(enemyX[i] > canvas.height) {
enemyY.splice(i,1);
enemyX.splice(i,1);
} else {
enemyY[i] += 5;
moveEnemy(enemyX[i],enemyY[i]);
}
}
for (i=0;i<bulletX.length;i++) {
if(bulletY[i] < 0) {
bulletY.splice(i,1);
bulletX.splice(i,1);
} else {
bulletY[i] -= 5;
moveBullet(bulletX[i],bulletY[i]);
for (ib=0;ib<enemyX.length;ib++) {
if(bulletX[i] + 50 < enemyX[ib] ||
enemyX[ib] + 50 < bulletX[i] ||
bulletY[i] + 50 < enemyY[ib] ||
enemyY[ib] + 50 < bulletY[i])
{
++score;
enemyY.splice(i,1);
enemyX.splice(i,1);
}
}
}
}
Objects:
function moveBullet(posX,posY) {
//console.log(posY);
ctx.arc(posX, (posY-150), 10, 0 , 2 * Math.PI, false);
}
function moveEnemy(posX,posY) {
ctx.rect(posX, posY, 50, 50);
ctx.fillStyle = '#ffffff';
ctx.fill();
}
Further to Ben's correction, for future reference it's better to do a line-line collision detection, rather than your point-box collision detection.
The reason for this is, say your enemy is small and your bullet is moving fast. There is always a chance the bullet will appear BEFORE the enemy in one frame, and then behind the enemy in the next, therefore never registering as a hit.
Testing for an intersect with the bullet path and an imaginary line on the enemy will be far more accurate.
ORI think I see a problem. You have the following code on your collision detection
if(bulletX[i] + 50 < enemyX[ib] ||
enemyX[ib] + 50 < bulletX[i] ||
bulletY[i] + 50 < enemyY[ib] ||
enemyY[ib] + 50 < bulletY[i])
This is straight ORs(||), and the +50 is on the less than side. That means that it should actually trigger as true whenever the bullet is not in the hitbox. I suspect that you instead want to have the +50s on the greater than side, and have the ORs(||) be ANDs(&&) instead.
I'm trying implement A* Start path finding in my games(which are written with JavaScript, HTML5 Canvas). Library for A* Start found this - http://46dogs.blogspot.com/2009/10/star-pathroute-finding-javascript-code.html and now I'm using this library for path finding.
And with this library, I'm trying write a simple test, but stuck with one problem.
I'm now done when in HTML5 canvas screen click with mouse show path until my mouse.x and mouse.y. Here is a screenshot:
(Pink square: Player, Orange squares: path until my mouse.x/mouse.y)
Code how I'm drawing the orange squares until my mouse.x/mouse.y is:
for(var i = 0; i < path.length; i++) {
context.fillStyle = 'orange';
context.fillRect(path[i].x * 16, path[i].y * 16, 16, 16);
}
My problem is I do not understand how to move my player until path goal.
I've tried:
for(var i = 0; i < path.length; i++) {
player.x += path[i].x;
player.y += path[i].y;
}
But with this code my player is not beung drawn.(When I run the code, player.x and player.y are equals to 0 and when I click with the mouse I get the path player blink and disappear)
Maybe anyone know how to solve this problem?
And I'm very very very sorry for my bad English language. :)
My Working Fiddle
This is what I currently use which is based off of my a*. The concept should be the same though. The a* function should return the path as an array, then you just need to iterate through the path on each player update and move them.
// data holds the array of points returned by the a* alg, step is the current point you're on.
function movePlayer(data, step){
step++;
if(step >= data.length){
return false;
}
// set the player to the next point in the data array
playerObj.x = data[step].x;
playerObj.y = data[step].y;
// fill the rect that the player is on
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(playerObj.x*tileSize, playerObj.y*tileSize, tileSize, tileSize);
// do it again
setTimeout(function(){movePlayer(data,step)},10);
}