Simple Javascript game "space invaders"-help wanted

My code currently looks like this:

It currently just says “Cannot read property ‘y’ of undefined” When I try to run my program. I want the spacebar to create and fire a laser across the screen. I suspect that part isn’t working and I would love some help.

Can you share your code?

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


1 Like

var player = {
	x: (totalWidth/2), y: (totalHeight-128)}
var enemycperrow = floor(totalWidth/50); // delar skärmen på 50 eftersom fienderna är 50x50 och avrundar ner
var enemies = [];

for (var i=0; i < enemycperrow; i++){
	enemies.push ({x: 0+50*i, y: 0, speed: 2, change: 1});

var lasers = [];

function PlayerMovement(){
	if(keyboard.d && (player.x+128)<totalWidth){
	if(keyboard.a && player.x>0) {

    picture(player.x, player.y, "")

function EnemyMovement(){
var i = 0;
while (i < enemycperrow)
	var enemy = enemies[i]//Går igenom alla fiender en åt gången
	enemy.x += (enemy.speed * enemy.change);//Här är början på rörelsen för fienderna
if (enemy.x<= 0 || enemy.x+50 >= totalWidth){
	enemy.change *=-1;
    enemy.y += 70;}
	picture(enemy.x, enemy.y, "")

function HandleLasers () {
	if ({
		lasers.push ({x: player.x+63, y: 93})
        var laser = {
			x: player.x , y: 93
	laser.y -= 15;
	rectangle(laser.x, laser.y, 2, 20, "red");


function update()


EnemyMovement ();

HandleLasers ();