Sidescroller jumping/collision (Not Java, but Javascript)

'ello guys,

So I have a question about some jumping and collision stuff in a sidescroller, so here goes:

I’m making a sidescroller for my bachelor project(A game for helping kids learn sequences of numders, such as 3,6,9 … 27, 30)

What I’m doing is exactly this(Couldn’t figure out a neat way of writing this, without pasting my HORRIBLE code)


Player.prototype.update = function(entities) {
	if(Keyboard.isPressed(Keyboard.D)) {
		this.velocity.x = 10;
	} else if(Keyboard.isPressed(Keyboard.A)) {
		this.velocity.x = -10;
	} else {
		this.velocity.x = 0;
	}

	if(!this.isJumping && Keyboard.isPressed(Keyboard.SPACE)) {
		this.isJumping = true;
		this.velocity.y = -this.jumpSpeed;
	}

	var move = (Math.abs(this.velocity.x) > Math.abs(this.velocity.y)) ? Math.abs(this.velocity.x) : Math.abs(this.velocity.y);

	for(var i = 0; i < move; i++) {
		var lastX = this.x,
			lastY = this.y;

		var nx = this.x + (this.velocity.x / move),
			ny = this.y + (this.velocity.y / move);

		var colX = false,
			colY = false;

		for(var x = 0; x < entities.length; x++) {
			if(entities[x].passable) {
				continue;
			}

			this.setX(nx);
			this.setY(ny);

			if(this.intersects(entities[x])) {

				this.setY(lastY);
				if(this.intersects(entities[x])) {
					nx = lastX;
					colX = true;
				}

				this.setX(nx);
				this.setY(ny);
				if(this.intersects(entities[x])) {
					ny = lastY;
					colY = true;
				}
			}
		}

		if(this.velocity.y > 0 && colY && !colX) {
			this.isJumping = false;
		}

		this.sprite.position.x = this.x;
		this.sprite.position.y = this.y;
	}

	if(this.velocity.y < this.grav) {
		this.velocity.y += this.grav;
	}
};

This sorta kinda works, except that you’re able to “cling” to walls, because … Well, I’m not perfectly sure, tbh, but I’m assuming that it’s somehow finding that it doesn’t collide with the wall on the side, but it collides with the wall piece below it.

(I’m aware that the code isn’t exactly epic, but it’s currently just for trying to get it do behave as it should, cleanup comes later, if there’s time for it)

Any clever tips would be most appreciated! :slight_smile: