Problem:
I'm trying to implement basic jumping to my 2D game engine, but have failed several times.
Basically what I've done so far is disabling gravity and using a separate function moving the player upwards. The problem with this is that it looks really bad.
I've checked a lot of threads about this, and found one way that should work.
This is by simply adding another force going upwards against gravity. This force should be greater than gravity, but should decrease until the force of gravity is greater again.
The problem is that I am unable to implement it.
My code is written in Javascript and uses html5 canvas for rendering.
Note! This code is only a part of the whole engine.
As for variables:
c_objects - array with all objects the player can collide with
player - object literal with position, width, movement speed, velocity, and the velocity multiplier.
Pseudo-code is good for me, but i'd love an answer in JS.
Code:
// physics module collision
function collision(obj_1, obj_2) {
var collision = Boolean(
obj_1.x <= (obj_2.x + obj_2.width)
&& obj_2.x <= (obj_1.x + obj_1.width)
&& obj_1.y <= (obj_2.y + obj_2.height)
&& obj_2.y <= (obj_1.y + obj_1.height)
);
// return position booleans
return {
collision: collision,
};
};
function movement(x, y) {
new_pos.x = player.x + x;
new_pos.y = player.y + y;
// check collision for all objects in collision array
var index;
var collisions = new Array();
for (index = 0; index < c_objects.length; ++index) {
var new_collision = engine.collision(new_pos, c_objects[index]);
collisions[index] = new_collision.collision;
}
var it_collides = collisions.indexOf(true) >= 0;
if (it_collides == false) {
player.x += x;
player.y += y;
}
}
// velocity & gravity module for adding gravity to an object
function gravity(modifier) {
if (player.gravity == true) {
var x = 0;
var y = 0;
x = 0;
y = +(player.velocity * modifier);
engine.movement(x, y);
if (player.velocity <= 450) {
player.velocity = (player.velocity * player.velocity_m);
}
else {
velocity = 450;
}
}
};