We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello, I am making my own version of space invaders for a school project. I am having issues getting this code to actually work. P5 isn't showing errors in the code, but it does show a suggestion to use [ ] instead of () (See code for the lines I'm referring to). When i switch to the square brackets, it shows an error. I'm not sure whats going on with that. Any help is appreciated. Thanks!!
//initializes bullets
var bullets = {
x: new Array(),
y: new Array(),
shot: new Array()
}
//initializes the ship
var ship = {
x: 625,
y: 475,
photo: loadImage("download.png")
}
function setup() {
createCanvas(1350,650);
//bullet1
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
//bullet2
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
//bullet3
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
}
//Controls
function updateShip()
{
//Right movement
if (keyIsDown(RIGHT_ARROW)) {
ship.x = ship.x+ 10;
if (ship.x >= 1350) {
ship.x = ship.x - 11;
}
}
//Left movement
if (keyIsDown(LEFT_ARROW)) {
ship.x = ship.x - 10;
if (ship.x <= 0) {
ship.x = ship.x + 11;
}
}
//Up movement
if (keyIsDown(UP_ARROW)) {
ship.y = ship.y - 10;
if (ship.y <= 350) {
ship.y = ship.y + 11;
}
}
//Down movement
if (keyIsDown(DOWN_ARROW)) {
ship.y = ship.y + 10;
if (ship.y >= 580) {
ship.y = ship.y - 11;
}
}
}
function drawShip()
{
ship.photo.resize(75,75);
image(ship.photo,ship.x-ship.photo.width/2,ship.y+ship.photo.height/2);
}
//Drawing the bullets
function drawBullets() {
fill(255);
rect(bullets.x[0],bullets.y[0], 5, 10);
rect(bullets.x[1],bullets.y[1], 5, 10);
rect(bullets.x[2],bullets.y[2], 5, 10);
}
//Controls the bullet movement
function updateBullets() {
bullets.y[0] = bullets.y[0] + 10;
}
//Checks if bullet is shot
function checkShoot() {
if (keyIsPressed && keyCode === 32) {
bullets.y[0] = ship.y;
}
}
function draw() {
background(0);
updateShip();
drawShip();
checkShoot();
updateBullets();
drawBullets();
}
Answers
HI
https://forum.Processing.org/two/discussion/15473/readme-how-to-format-code-and-text
bump. (if that works)
In p5.js, we can't use its API, like loadImage(), before setup() or preload() starts:
http://p5js.org/reference/#/p5/preload
Agree with @GoToLoop that your loadImage before setup is an issue. Easily remedied - since you have the object in place you can later (in preload or setup) use:
ship.photo = loadImage("download.png");
Thanks for all the help guys!