How do i make my character not go to space in p5js - javascript

When I run my code I when I jump for some reason when I press a on the keyboard my character(the purple rectangle) goes into space
Here is the code:
//Global
//Game control
var stage = 0; // keeps track of which function to run
//Player
var p1X = 400; // p1 for player one
var p1Y = 375;
var pWidth = 30;
var pHeight = 70;
//Boxes (Platforms)
var b1X = 200; // b1 for box one
var b1Y = 300;
var bWidth = 200;
var bHeight = 40;
//Gravity
var jump = false; //are we jumping?
var direction = 1;
var velocity = 2;
var jumpPower = 10;
var fallingSpeed = 2;
var minHeight = 375;
//Setup
function setup() {
createCanvas(800, 500);
rectMode(CENTER);
textAlign(CENTER);
}
//Close setup
//Draw
function draw() {
//Call functions
if (stage == 0) {
game();
} //Close = 0
keyPressed();
gravity();
}
//Close draw
//////////Game
function game() {
//apperence of game
background(150, 230, 240); //Sky blue
//grass
noStroke();
fill(100, 200, 75); //green
rect(width / 2, 450, width, 100);
//window frame
noFill();
stroke(0);
strokeWeight(15);
rect(width / 2, height / 2, width, height);
//Draw box
stroke(0);
strokeWeight(5);
fill(255, 120, 0); //Orange
rect(b1X, b1Y, bWidth, bHeight);
//Draw Character
stroke(0);
fill(150, 0, 170); //Purple
rect(p1X, p1Y, pWidth, pHeight);
} //Close game
function gravity() {
if (p1Y >= minHeight && jump == false) {
p1Y = p1Y;
} else {
p1Y = p1Y + (direction * velocity);
}
if (jump == true) {
velocity = -jumpPower;
} else {
velocity = fallingSpeed;
}
}
function keyPressed() {
if (keyIsDown(LEFT_ARROW)) {
p1X = p1X - 5; //Move Left
} //Close Left
if (keyIsDown(RIGHT_ARROW)) {
p1X = p1X + 5; //Move Right
if (keyIsDown(UP_ARROW)) {
jump = true;
}
} //close keypressed
}
function keyTyped() {
if (keyIsDown(65)) {
jump = true;
} else {
jump = false;
}
}
canvas {
/* make the canvas fit in the tiny StackOverflow snippet iframe */
transform-origin: top left;
transform: scale(0.35);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
I want my player to jump and move left that's all but for some reason p5js says no and doesn't explain way it goes to space. I tried to add some more code but it still went to space but when I press another key after pressing a the character comes down

There are a few things in your code that I would change, but for jumping, here's my suggestion:
Change the velocity during the jump. When you jump in real life, gravity will constantly reduce your (vertical) velocity until you hit the ground. In this situation, you want to do the same thing: when you first jump, set the vertical velocity to a certain value. Until you hit a surface, continue to reduce the value of velocity (even to negative numbers).

Basically just translating what #jstl suggested into code, apply vertical velocity to the player position for each frame like so:
function gravity() {
let newTime = millis();
let timeDeltaSeconds = (newTime - time) / 1000;
time = newTime;
p1Y += velocity * timeDeltaSeconds * pixelsPerMeter;
// ...
}
And update velocity based on acceleration due to gravity like so:
function gravity() {
// ...
if (p1Y >= minHeight) {
// Impact with the ground, zero out velocity.
velocity = 0;
p1Y = minHeight;
}
if (p1Y < minHeight) {
velocity -= gravityAccel * timeDeltaSeconds;
}
}
With this in place "jumping" is just applying a sudden impulsive increase to velocity:
function keyTyped() {
if (keyIsDown(65) && p1Y == minHeight) {
// only "jump" when we're actually touching the ground.
velocity = jumpPower;
}
}
Here's a runnable example:
//Global
//Game control
let stage = 0; // keeps track of which function to run
//Player
let p1X = 400; // p1 for player one
let p1Y = 375;
let pWidth = 30;
let pHeight = 70;
//Boxes (Platforms)
const b1X = 200; // b1 for box one
const b1Y = 300;
const bWidth = 200;
const bHeight = 40;
//Gravity
// vertical velocity
let velocity = 0;
const jumpPower = 17;
// I'm not sure why but the real value for acceleration due to gravity (9.8)
// just doesn't look right.
const gravityAccel = 28;
// Player will be impacting the ground
const minHeight = 375;
// Number of pixels to move for every meter. Note that this is negative
// since the Y axis goes from 0 at the top to height at the bottom, so
// when we have a positive vertical velocity we want to decrease the y
// value.
const pixelsPerMeter = -30;
let time;
//Setup
function setup() {
createCanvas(800, 500);
rectMode(CENTER);
textAlign(CENTER);
time = millis();
}
//Close setup
//Draw
function draw() {
//Call functions
if (stage == 0) {
game();
} //Close = 0
movement();
gravity();
}
//Close draw
//////////Game
function game() {
//apperence of game
background(150, 230, 240); //Sky blue
//grass
noStroke();
fill(100, 200, 75); //green
rect(width / 2, 450, width, 100);
//window frame
noFill();
stroke(0);
strokeWeight(15);
rect(width / 2, height / 2, width, height);
//Draw box
stroke(0);
strokeWeight(5);
fill(255, 120, 0); //Orange
rect(b1X, b1Y, bWidth, bHeight);
//Draw Character
stroke(0);
fill(150, 0, 170); //Purple
rect(p1X, p1Y, pWidth, pHeight);
} //Close game
function gravity() {
let newTime = millis();
let timeDeltaSeconds = (newTime - time) / 1000;
time = newTime;
p1Y += velocity * timeDeltaSeconds * pixelsPerMeter;
if (p1Y >= minHeight) {
// Impact with the ground.
velocity = 0;
p1Y = minHeight;
}
if (p1Y < minHeight) {
velocity -= gravityAccel * timeDeltaSeconds;
}
}
function movement() {
if (keyIsDown(LEFT_ARROW)) {
p1X = p1X - 5; //Move Left
} //Close Left
if (keyIsDown(RIGHT_ARROW)) {
p1X = p1X + 5; //Move Right
} //close keypressed
}
function keyTyped() {
if (keyIsDown(65) && p1Y == minHeight) {
// only "jump" when we're actually touching the ground.
velocity = jumpPower;
}
}
canvas {
/* make the canvas fit in the tiny StackOverflow snippet iframe */
transform-origin: top left;
transform: scale(0.35);
}
body {
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>

Related

How do I make my health bar decrease based on damage received?

So basically I'm trying to create a shooter game. But a problem arose while trying to implement a health bar function for the player. Although I did manage to create a health bar that reduces or decreases based on its value, I can't change its value via code. Any suggestions would be appreciated.
I have created a player and enemy sprite who constantly shoot bullet sprites at each other. I am trying to make the player sprite's health bar go down when the enemy sprite's bullet (bullet_e) makes contact with it.
I'm considerably new to JavaScript, so please forgive any rookie mistakes.
Here's the script (I pasted the entire code, in case putting parts of the code cause problems):
var bg;
var player, playerImg;
var bullet_e, bulletImg;
var missile, missile_e, missileImg, missile_e_img;
var fireBall, fireBall_img;
var bg;
var enemy, enemyImg;
var trig1, trig2;
var health = 100;
var maxHealth = 100;
function preload() {
playerImg = loadImage("Assets/TBM-3.png");
bulletImg = loadImage("Assets/Bullets_01.png");
missileImg = loadImage("Assets/missile_01.png");
missile_e_img = loadImage("Assets/missile_02.png");
fireBall_img = loadImage("Assets/fireBall_01.png");
bg = loadImage("Assets/Backgrounds/BG_07.png");
enemyImg = loadImage("Assets/Enemy_FighterJet_Ba.png");
}
function setup() {
createCanvas(windowWidth, windowHeight);
player = createSprite(width / 2, height / 2 + 270);
player.addImage("player", playerImg);
player.scale = 0.5;
enemy = createSprite(windowWidth / 2 + 600, windowHeight / 2 - 300);
enemy.addImage("enemy", enemyImg);
enemy.scale = 0.6;
trig1 = createSprite(windowWidth, windowHeight - 650);
trig1.scale = 0.7;
trig1.visible = false;
trig2 = createSprite(windowWidth / 100, windowHeight - 650);
trig2.scale = 0.7;
trig2.visible = false;
}
function draw() {
background(bg, windowWidth, windowHeight);
//Health Bar
playerController();
enemyController();
//spawnBullets_p()
spawnBullets_e();
//checkCollisions()
updateHealth();
drawSprites();
}
function playerController() {
// Locomotion
if (keyDown(RIGHT_ARROW)) {
player.x = player.x + 8;
}
if (keyDown(LEFT_ARROW)) {
player.x = player.x - 8;
}
if (keyDown(UP_ARROW)) {
player.y = player.y - 6;
}
if (keyDown(DOWN_ARROW)) {
player.y = player.y + 6;
}
//Attacks
if (keyWentDown("space")) {
// Right wing
missile = createSprite(player.x + 39, player.y - 29);
missile.addImage("missile", missileImg);
missile.scale = 0.08;
missile.velocityY = -8;
missile.lifetime = 80;
// Left Wing
missile = createSprite(player.x - 39, player.y - 29);
missile.addImage("missile", missileImg);
missile.scale = 0.08;
missile.velocityY = -8;
missile.lifetime = 80;
}
}
function spawnBullets_p() {
if (frameCount % 4 === 0) {
bullet_p = createSprite(player.x + 37, player.y - 29);
bullet_p.addImage("bullet", bulletImg);
bullet_p.scale = 0.09;
bullet_p.velocityY = -30;
bullet_p.lifetime = 30;
bullet_p = createSprite(player.x - 37, player.y - 29);
bullet_p.addImage("bullet", bulletImg);
bullet_p.scale = 0.09;
bullet_p.velocityY = -30;
bullet_p.lifetime = 30;
}
}
function spawnBullets_e() {
if (frameCount % 6 === 0) {
bullet_e = createSprite(enemy.x + 33, enemy.y + 68);
bullet_e.addImage("bullet", bulletImg);
bullet_e.scale = 0.09;
bullet_e.velocityY = 30;
bullet_e.lifetime = 30;
bullet_e = createSprite(enemy.x - 33, enemy.y + 68);
bullet_e.addImage("bullet", bulletImg);
bullet_e.scale = 0.09;
bullet_e.velocityY = 30;
bullet_e.lifetime = 30;
if (bullet_e.isTouching(player)) {
health = health - 5;
bullet_e.destroyed();
}
console.log(health);
}
}
function enemyController() {
// locomotion
if (enemy.isTouching(trig1)) {
enemy.velocityX = -4;
}
if (enemy.isTouching(trig2)) {
enemy.velocityX = 4;
}
//Attack
if (frameCount % 100 === 0) {
// Right wing
missile_e = createSprite(enemy.x + 50, enemy.y + 68);
missile_e.addImage("missile2", missile_e_img);
missile_e.scale = 0.08;
missile_e.velocityY = +8;
missile_e.lifetime = 80;
// Left Wing
missile_e = createSprite(enemy.x - 50, enemy.y + 68);
missile_e.addImage("missile2", missile_e_img);
missile_e.scale = 0.08;
missile_e.velocityY = +8;
missile_e.lifetime = 80;
}
if (frameCount % 300 === 0) {
fireBall = createSprite(enemy.x, enemy.y + 30);
fireBall.addImage("fireBall", fireBall_img);
fireBall.scale = 0.09;
fireBall.velocityY = 5;
fireBall.lifetime = 90;
}
}
function checkCollisions() {
if (bullet_e.isTouching(player)) {
health = -5;
}
}
function updateHealth() {
stroke(0);
strokeWeight(4);
noFill();
rect(10, 10, 200, 20);
noStroke();
fill(255, 0, 0);
rect(10, 10, map(health, 0, maxHealth, 0, 200), 20);
}
i see your code and in this function
function checkCollisions()
{
if(bullet_e.isTouching(player))
{
health = -5;
}
}
the health variable is change to a value of -5 instead of decreasing that should be 95 and so on. Try this
function checkCollisions()
{
if(bullet_e.isTouching(player))
{
health -=5;
}
}
or health = health -5;
if the value still not changing. Try to put console.log("function name") to your functions to know if its called or not. Sometimes troubles are hidden on logical statements that hard to notice that the values or the condition dint meet properly.

How to stop an object from jumping past a certain point?

Catbus game
I'm trying to make my cat only jump once until it lands back on the ground. I've tried to add a statement that makes it only go to a certain point, but the velocity keeps working against it. It begins to act like a basketball that has been bounced to much. I wouldn't want to add a collider (even though I have debated it). It would just make it worse...
The 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 bing; //for music
let cat;
var mode; //determines whether the game has started
let gravity = 0.2; //jumping forces
let velocity = 0.1;
let upForce = 6;
let startY = 730; //where cat bus jumps from
let startX = 70;
var font1; //custom fonts
var font2;
p5.disableFriendlyErrors = true; //avoids errors
function preload() {
bgImg = loadImage("backgwound.png"); //importing background
bing = loadSound("catbus theme song.mp3"); //importing music
font1 = loadFont("Big Font.TTF");
font2 = loadFont("Smaller Font.ttf");
}
function setup() {
createCanvas(1000, 1000); //canvas size
img = loadImage("backgwound.png"); //background in
x2 = width;
bing.loop(); //loops the music
cat = {
//coordinates for catbus
x: startX,
y: startY,
};
catGif = createImg("catgif.gif"); //creates catbus
catGif.position(cat.x, cat.y); //creates position
catGif.size(270, 100); //creates how big
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("white"); //text colour
if (mode == 0) {
textSize(20);
textFont(font1);
text("press SPACE to start the game!", 240, 500); //what text to type
}
if (mode == 0) {
textSize(35);
textFont(font2);
text("CATBUS BIZZARE ADVENTURE", 90, 450); //what text to type
}
cat.y = cat.y + velocity; //code for jumping
velocity = velocity + gravity;
if (cat.y > startY) {
velocity = 0;
// cat.y = startY;
}
catGif.position(cat.x, cat.y);
}
function keyPressed() {
if (keyCode === 32) { //spacebar code
// if ((cat.y = 730)) {
// cat.y > 730;
mode = 1;
velocity += -upForce;
}
// }
}
You can simply do this to the keyPressed function
function keyPressed() {
if (keyCode === 32 && velocity == 0) { //spacebar code
// if ((cat.y = 730)) {
// cat.y > 730;
mode = 1;
velocity += -upForce;
}
}

How would I make a gif jump, while implementing gravity and a ground y-variable?

CatBus Code Link
I'm trying to make my gif "jump", while also coming back to rest at a y value of 730. No more, no less. It would work to the same extent as the Dinosaur game, when the wifi is out. I'd like to include a gravity function as well. I'm not sure how to do that. (I'm VERY new to coding.) Any tips?
[Code is below]
let img; //background
var bgImg; //also the background
var x1 = 0;
var x2;
var scrollSpeed = 4; //how fast background is
let bing; //for music
let cat = { //coordinates for catbus
x:70,
y:730
}
var mode; //determines whether the game has started
function preload() {
bgImg = loadImage("backgwound.png"); //importing background
bing=loadSound('catbus theme song.mp3'); //importing music
}
function setup() {
createCanvas(1000, 1000); //canvas size
img = loadImage("backgwound.png"); //background in
x2 = width;
bing.loop() //loops the music
catGif=createImg("catgif.gif") //creates catbus
catGif. position(cat.x, cat.y) //creates position
catGif. size(270,100) //creates how big
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("white") //text colour
if(mode==0){
text('Press SPACE to start the game.',150,500); //what text to type
}
if(mode==0){
text('CATBUS BIZZARE ADVENTURE',135,450) //what text to type
}
}
function pickRandom() {
x = random(20, width - 20);
}
I've updated your p5.js sketch to point you in the right direction.
I've introduced a few variables that are defined at the top of your code before setup:
let gravity = 0.1;
let velocity = 0;
let upForce = 3;
let startY = 730;
let startX = 70;
...
You can tweak these numbers to fit your game. But the basic premise here is that each frame we add the velocity to the cat.y and the velocity is incremented each frame by the gravity:
cat.y = cat.y + velocity;
velocity = velocity + gravity;
However, there's a caveat, we don't want to add the velocity to the cat.y if the cat is at its startY, as startY is the grass:
if (cat.y > startY) {
velocity = 0;
cat.y = startY;
}
catGif.position(cat.x, cat.y); // reposition the gif
And lastly, when you hit spacebar, jump!
(And get rid of the starting screen)
function keyPressed() {
if (keyCode === 32) {
//spacebar
mode = 1;
velocity -= upForce;
}
}

Motion effect for standing object

I have trying to achieve motion effect for the standing object.
I assume that my object will be able to go to the right or the left for example.
And I wanna make illusion like that object is still moving. Even if currently is not moving. (Meanwhile background can moving still...)
'use strict';
const pressedKeys = [];
const canvas = document.querySelector('#game');
const ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 150;
class Player
{
xPosition = 150;
yPosition = 50;
speed = 5;
isMoving = false;
update(pressedKeys)
{
if (pressedKeys['ArrowLeft']) {
this.xPosition -= this.speed;
} else if (pressedKeys['ArrowRight']) {
this.xPosition += this.speed;
}
}
draw(ctx)
{
ctx.fillStyle = '#2976f2';
ctx.fillRect(this.xPosition, this.yPosition, 30, 30);
}
}
const player = new Player();
function animate()
{
window.requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height)
if (player.isMoving) {
player.update(pressedKeys);
}
player.draw(ctx);
}
animate();
window.addEventListener('keyup', function (event) {
delete pressedKeys[event.key];
player.isMoving = false;
})
window.addEventListener('keydown', function (event) {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowRight':
pressedKeys[event.key] = true;
player.isMoving = true;
break;
}
})
canvas {
border: 1px solid blue;
}
<canvas id="game"></canvas>
Usually this kind of effect is done by constantly duplicating the desired object, move it to the exact same screen position and ultimately fade it out over time e.g. within one second.
In your case though we can simplify things a bit since you want to keep that "motion blurred" look even if it ain't moving.
So first we need to another property to your Player class oldX. It holds the position of the object before a movement occured. By subtracting oldX from x we can determine if the object is moving to the left or to the right - so we know where to put the trailing duplicates.
If we know the direction, we can start creating duplicates using a simple for loop like:
for (var a = 0; a < 7; a++) {
ctx.fillRect(this.x - (this.x - this.oldX) / this.speed * a * 2, this.y, 30, 30);
}
this will create seven equal looking squares - so it won't look good yet. The duplicate next to the original should have almost the same color while the last one should almost blend with the background. To do this we can use the globalAlpha property of the canvases context. A value of 1 is opaque while 0 is completely transparent.
Putting it all together:
const keys = [];
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 150;
class Player {
x = 150;
y = 50;
oldX = 150;
speed = 5;
moving = false;
update(keys) {
this.oldX = this.x;
if (keys['ArrowLeft']) {
this.x -= this.speed;
} else if (keys['ArrowRight']) {
this.x += this.speed;
}
}
draw(ctx) {
ctx.fillStyle = '#2976f2';
ctx.fillRect(this.x, this.y, 30, 30);
ctx.save();
for (var a = 0; a < 7; a++) {
ctx.globalAlpha = 0.5 - (a / 7) * 0.5;
ctx.fillRect(this.x - (this.x - this.oldX) / this.speed * a * 2, this.y, 30, 30);
}
ctx.restore();
}
}
const player = new Player();
function animate() {
window.requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height)
if (player.moving) {
player.update(keys);
}
player.draw(ctx);
}
animate();
window.addEventListener('keyup', function(event) {
delete keys[event.key]
player.moving = false;
})
window.addEventListener('keydown', function(event) {
switch (event.key) {
case 'ArrowLeft':
case 'ArrowRight':
keys[event.key] = true;
player.moving = true;
break;
}
})
canvas {
border: 1px solid blue;
}
<canvas id="game"></canvas>

How to rotate/transform image using arrow keys

I'm relatively new to canvas and I'm trying to make a space ship type game. I have everything else I'd like down, except for the ship turning itself. I want to make the image of the ship rotate when the arrow keys are clicked.
So if the left arrow key is clicked, it will turn to face the left, and the right arrow key is clicked it will turn to face the right, and so on. I really can't figure this out, if anyone can show me how to do this I would really appreciate it.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
/*Variable to store score*/
var score = 0;
/*Variable that stores the players object properties*/
var x = 50;
var y = 100;
var speed = 6;
var sideLength = 50;
/*Flags to track when keypress is active*/
var down = false;
var up = false;
var left = false;
var right = false;
/*Variables that store target position and size*/
var targetX = 0;
var targetY = 0;
var targetLength = 25;
/*If a number is within range b to c*/
function isWithin(a, b, c) {
return (a > b && a < c)
}
var countDown = 30;
/*Id to track set time*/
var id = null;
/*Listening for if one of the keys is pressed*/
canvas.addEventListener('keydown', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = true;
}
if (event.keyCode === 38) {
up = true;
}
if (event.keyCode === 37) {
left = true;
}
if (event.keyCode === 39) {
right = true;
}
});
/*Listening for if one of the keys is released*/
canvas.addEventListener('keyup', function (event) {
event.preventDefault();
console.log(event.key, event.keyCode);
if (event.keyCode === 40) {
down = false;
}
if (event.keyCode === 38) {
up = false;
}
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 39) {
right = false;
}
});
/*Function to show menu*/
function menu() {
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Collect The Thing', canvas.width / 2, canvas.height / 4);
context.font = '30px Arial';
context.fillText('Press to Start', canvas.width / 2, canvas.height / 2);
/*Listen for click to start game*/
canvas.addEventListener('click', startGame);
}
/*Function to start the game*/
function startGame() {
/*reduce the countdown timer every 1 second*/
id = setInterval(function () {
countDown--;
}, 1000)
/*remove click events*/
canvas.removeEventListener('click', startGame);
moveTarget();
draw();
}
/*Show game over screen*/
function endGame() {
/*stop the countdown*/
clearInterval(id);
/*clear game board*/
erase();
context.fillStyle = '#000000';
context.font = '36px Arial';
context.textAlign = 'center';
context.fillText('Finale Score: ' + score, canvas.width / 2, canvas.height / 4);
}
/*Move target to random location in canvas*/
function moveTarget() {
targetX = Math.round(Math.random() * canvas.width - targetLength);
targetY = Math.round(Math.random() * canvas.height - targetLength);
}
/*Clear the Canvas*/
function erase() {
context.fillStyle = '#FFFFFF';
context.fillRect(0, 0, 600, 500);
}
/*Main animation drawing loop with game logic*/
function draw() {
erase();
/*Move the player sqaure*/
if (down) {
y += speed;
}
if (up) {
y -= speed;
}
if (right) {
x += speed;
}
if (left) {
x -= speed;
}
if (y + sideLength > canvas.height) {
y = canvas.height - sideLength;
}
if (y < 0) {
y = 0;
}
if (x < 0) {
x = 0;
}
if (x + sideLength > canvas.width) {
x = canvas.width - sideLength;
}
/*Collide with target*/
if (isWithin(targetX, x, x + sideLength) || isWithin(targetX + targetLength, x, x + sideLength)) {
if (isWithin(targetY, y, y + sideLength) || isWithin(targetY + targetLength, y, y + sideLength)) {
/*respawn target in a random location*/
moveTarget();
/*Increase score by 1*/
score++;
}
}
//Draw player object
context.fillRect(x, y, sideLength, sideLength);
context.drawImage(baseImage, x, y, sideLength, sideLength);
/*Draw target sqaure*/
context.fillStyle = '#00FF00';
context.fillRect(targetX, targetY, targetLength, targetLength);
//Timer and Score
context.fillStyle = '#000000';
context.font = '24px Arial';
context.textAlign = 'left';
context.fillText('Score: ' + score, 10, 24);
context.fillText('Time Remaining: ' + countDown, 10, 50);
if (countDown <= 0) {
endGame();
} else {
window.requestAnimationFrame(draw);
}
}
baseImage= new Image();
baseImage.src='xwing3.png';
baseImage.onload= function() {
menu();
}
canvas.focus();
I think in this regard you have two options.
You could have a sprite for every direction that you want the ship to face, then when you draw the image, you could choose the sprite that matches.
if(left == true) {baseImage.src='xwing3left.png';}
You could use the canvas rotate() method. This would make things more complicated, but it actually rotates the canvas and could give more opportunity to experiment.
It actually applies a transformation matrix to the canvas before it draws so you could do things like:
context.rotate(45);
context.fillRect(x,y,width,height);
Just be careful, because rotate always occurs around the origin, so you might need to use translate() as well to make it work the way you expect.
Hope this helps! :)

Categories