Code a jump like in the game 'Winterbells' - javascript

How would one go about coding a jump like in this game? I've got some working code already (made in Adobe Edge) but the way it's programmed it won't start another jump while mid-air. This is what I've got atm:
var velocityY = 0;
var gravity = 0.5;
var onGround = false;
var fps = 60;
function StartJump()
{
if(onGround)
{
velocityY = -13.0;
onGround = false;
}
}
function EndJump()
{
if(velocityY < -6,0)
velocityY = -6,0;
}
var positionY = sym.$("ball").position().left;
Loop();
function Loop()
{
Update();
setTimeout(Loop, 1000/fps);
}
function Update()
{
velocityY += gravity;
positionY += velocityY;
if(positionY > 730)
{
positionY = 730;
velocityY = 0;
onGround = true;
}
sym.$("ball").css("top", positionY + "px");
console.log(velocityY);
}
The top value 730 is where "ball" starts on the ground. StartJump() is called on the event 'mousedown' and EndJump() on 'mouseup'. I can't figure out how to change the code so I can make it jump while mid-air (as in when it collides with sth, like how in the game the bunny hits the bell).

Related

Player Jumping Glitch

this is my first post! With that in mind, if I need to add anything more than what is below, please let me know. Thank you!
I am currently working to make a platformer game in Javascript where a player can move using arrow keys. Currently, my left and right movements, as well as my player gravity, works. However, when I jump, I am unable to provide smooth jumping movements. originally, I tried simply moving my player's y value higher.
if (up) {
this.y -= 100;
}
However, this makes the player "teleport" upwards, rather than look like an actual jump. To fix this, I reused my gravity code to overcome the gravitational force until a certain limit, making the player look like they are smoothly jumping until they reach a certain height. Below is my code.
if (up) { // This if statement is apart of another function, did not include
this.can_jump = false;
this.jumping = true; this.jump();
}
jump() { // Overcome the gravitational force, but jump force slowly lowers
this.y -= (this.gravity * this.velocity) * 3;
this.gravity -= 0.1;
this.velocity -= 0.1;
this.check();
this.check_jump(this.jumping);
}
check_jump(jumping) {
if (jumping) {
if (this.x < 500) { // While player is less than 500, keep jumping
this.jumping = false;
this.gravity = 2;
this.velocity = 2;
this.can_jump = true;
}
}
}
Additionally, here is the code regarding player collisions and gravity.
gravityEffect() {
this.y += (this.gravity * this.velocity);
this.check();
}
check() {
// Too far up
if (this.y <= 70) { this.y = 70; }
// Too far down
if (this.y >= 600) { this.y = 600; }
// Too far left, teleports to other side
if (this.x < 0) { this.x = 1200; }
// Too far right, teleports to other side
if (this.x > 1200) { this.x = 0; }
}
However, when testing this, my player not only keeps jumping upwards, but also does not do so smoothly (it looks like it is glitching). Here is a link to an mp4 file download (screen recording) showcasing the glitch: https://www.mediafire.com/file/jtqh3lca72vj8nz/%25F0%259D%2590%258C%25F0%259D%2590%25B2_%25F0%259D%2590%2586%25F0%259D%2590%25AB%25F0%259D%2590%259A%25F0%259D%2590%25AF%25F0%259D%2590%25A2%25F0%259D%2590%25AD%25F0%259D%2590%25B2_-_Google_Chrome_2021-04-28_19-59-08.mp4/file
Also, here is a copy of my current code (zipped), if running the program helps: https://www.mediafire.com/file/r5ewoxtb4n57htz/game.zip/file
Please let me know what is wrong. Also, if there is a different or more efficient method of simulating player jumping, please make me aware of it. Thank you for your time.
While trying to keep the code mostly the same I made some changes.
First and formost I changed how you had the controller written. Unless your intention was for the up/down/left/right arguments to stay true then you need a method for them to kick back to false. This controller class will do that.
// Apply classes to empty variables
console.log("Creating player...");
player = new Player();
console.log("Creating world...");
world = new World();
console.log("Creating Controller...")
controller = new Controller();
// Draw canvas with set size
console.log("Creating game screen...");
createCanvas(1000, 750);
}
class Controller {
constructor() {
this.up = false;
this.down = false;
this.right = false;
this.left = false;
let keyEvent = (e) => {
if (e.code === 'ArrowUp') { this.up = e.type === 'keydown' }
if (e.code === 'ArrowRight') { this.right = e.type === 'keydown' }
if (e.code === 'ArrowDown') { this.down = e.type === 'keydown' }
if (e.code === 'ArrowLeft') { this.left = e.type === 'keydown' }
}
window.addEventListener('keydown', keyEvent)
window.addEventListener('keyup', keyEvent)
}
}
Since we changed that we'll have to change the Player Class very slightly.
I've set the X and Y velocity to 0 and we'll increment those once a button is pressed. The additional update function will update your X and Y based on that.
Player Class
class Player {
// Setup player attributes
constructor() {
this.x = 100;
this.y = 395;
this.width = 50;
this.height = 50;
this.jumping = false;
this.color = "#ffdb15";
this.gravity = 2;
this.velocityY = 0;
this.velocityX = 0; //changed this from speed
this.points = 0;
}
move() {
// Reverse gravity to upwards, change player's color
if (controller.up && !this.jumping) { this.jumping = true; this.jump(); this.color = this.getRandomColor(true); }
// Reverse gravity to downwards, change player's color
if (controller.down) { this.color = this.getRandomColor(false); }
// Go left
if (controller.left) { this.velocityX -= 1 }
// Go right
if (controller.right) { this.velocityX += 1 }
}
jump() {
this.velocityY -= 35;
}
check() {
// Too far up
if (this.y <= 70) { this.y = 70; }
// Too far down
if (this.y >= 600) { this.y = 600; this.jumping = false } //once collision player can jump again
// Too far left, teleports to other side
if (this.x < 0) { this.x = 1200; }
// Too far right, teleports to other side
if (this.x > 1200) { this.x = 0; }
}
// Get a random player color
getRandomColor(isMoving) {
if ((this.y === 70 || this.y === 600) && isMoving) {
// Explanation: Each color has RGB values from 0 to 255, or 256 total options
// Since colors start from "000000" and go until "FFFFFF", there are ((256^3) - 1) possibilities
// (256^3) - 1 = 16777215
// Use this number, and a random number from Math.Random(), to get a random color
// Idea from: https://css-tricks.com/snippets/javascript/random-hex-color/
this.color = Math.floor(Math.random() * 16777215).toString(16);
return "#" + this.color;
} else { return this.color; }
}
show() {
// Show player
fill(this.color);
strokeWeight(0);
rect(this.x, this.y, this.width, this.height);
}
update() {
this.velocityY += this.gravity;
this.x += this.velocityX;
this.y += this.velocityY;
this.velocityY *= 0.9;
this.velocityX *= 0.9; //provides a sliding slow down once button is released.
this.move();
this.check();
}
}
The draw function is the same but replace gravity with update
function draw() {
world.generate();
player.update();
player.show();
}
This should get you where you want to go with it.
Do you have a variable for y speed? i've found the best way to create a fairly normal looking jump would be to set the y speed to a set number, EG: -4. My personal favorite method for realistic player jumping and gravity would be as follows, but can be easily modified for your uses:
//Initial y position
var y=height/2;
//This is how far the player moves each frame
var ys=0;
//This is how intense the gravity is.
var yss=0.1;
function draw(){
y+=ys;
//yss can be replaced with some arbitrary number if you don't plan on changing it(EG: for collisions)
ys+=yss;
//Then to jump, something like this
if(mouseIsPressed){
ys=-4;
}
//Heck, if you wanted to flip gravity you could do this
//yss*=-1;
//and bouncing would look like this
//ys*=-0.9;
}
Let me know if there is anything I can clarify or help with!

Javascript "ball" bouncing

I am a JS noob. I am getting into browser game programming and wanted to make a quick example of a ball dropping and bouncing just to learn. For some reason, when I created a jsfiddle my code actually didn't work, the onclick event for my div id="ball" didn't seem to be attaching, but when I run it in my browser it does. But that is not my question.
In this code, the user clicks the ball, which is just a div with a black bg. The div then follows the users cursor, and when the user clicks a second time, the div begins to fall towards the bottom of the window. When it hits the bottom, it should bounce back up, with an apex half the distance between the y coordinate of where it was originally dropped and the bottom of window. So if it was dropped at y position 600 and the bottom of the page is 800, the apex for the first bounce should be 700. The 2nd bounce, the apex would be 750. 3rd bounce, 775. You get the idea. Can someone help me a bit here? I am guessing I need to increment a counter each time the ball hits the bottom?
<html>
<head>
<style>
#ball {
width: 50px;
height: 50px;
background-color: black;
position: absolute;
}
</style>
<script>
window.onload = function() {
var ballClicked = false;
var ballFalling = false;
var ballX = 100;
var ballY = 100;
var timesBounced = 0;
var bounceApex = 0;
var startingDropHeight = 0;
var intervalVar;
var ball = document.getElementById("ball");
ball.style.left = ballX;
ball.style.top = ballY;
ball.onclick = function() {
if (ballClicked == false) {
ballClicked = true;
} else {
ballClicked = false;
ballFalling = true;
startingDropHeight = ballY;
intervalVar = setInterval(function(){dropBall()} , 5);
}
};
document.onmousemove = function(e) {
if (ballClicked == true) {
ballX = e.pageX;
ballY = e.pageY;
ball.style.left = ballX;
ball.style.top = ballY;
}
};
function dropBall() {
if (ballFalling == true) {
ballY = ballY + 1;
ball.style.top = ballY;
if (ballY == window.innerHeight - 50) {
timesBounced = timesBounced + 1;
bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;
ballFalling = false;
if (bounceApex > window.innerHeight - 50) {
clearInterval(intervalVar);
}
};
} else {
ballY = ballY - 1;
ball.style.top = ballY;
if (ballY == bounceApex) {
ballFalling = true;
};
}
};
};
</script>
</head>
<body>
<div id="ball"></div>
</body>
</html>
When adding left and top styles, you need to specify the unit as well. So, instead of:
ball.style.left = 100;
it should be:
ball.style.left = "100px";
I've fixed that in your code and made a working jsfiddle, will improve the bouncing in a bit. See it here: http://jsfiddle.net/12grut99/
About the repetitive bouncing, this line is the issue:
bounceApex = (startingDropHeight + (window.innerHeight - 50)) / 2;
You're always calculating the apex based on the original drop height, yet after every bounce, the drop height should be the previous bounceApex (the highest point the ball reached).

gravity inside html5 canvas

I'm trying to do a copy of the original super mario game using html5 canvas just for fun and to learn more about the canvas tool and it's animation but i am stuck at making Mario do it's jump here is my jsfiddle : http://jsfiddle.net/2tLCk/1/
how should i fix my up function to make mario jump and return back to the ground like in this website http://blog.nihilogic.dk/ i tried to understand it's code but i couldn't ?
if (keydown.up) {
vy += gravity;
character.CurentPos = 11;
character.x += character.speed;
character.y += vy;
}
Here's a jumping Mario http://jsfiddle.net/2tLCk/22/.
If jumping is 1 - going up. If jumping is 2 - going down.
if(jumping){
if(jumping == 1) {
if(character.y > 140) character.y -= gravity;
else jumping = 2;
} else if(jumping == 2) {
if(character.y < 184) character.y += gravity;
else{
character.y = 184;
jumping = false;
character.CurentPos = 6;
}
}
}else if(keydown.up) {
jumping = 1;
character.CurentPos = 11;
}
And you would probably want to use this https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame instead of setInterval().
You basically want the gravitiy to be always active, not only when pushing the down key.
When jumping (key up) you have to add to vy. Like this:
if(keydown.up) {
vy += -2;
}
vy += gravity;
if(character.y > 184) { // simple collision detection for ground floor
vy = 0;
character.y = 184;
}
//character.CurentPos = 11;
//character.x += character.speed;
character.y += vy;
see http://jsfiddle.net/pjQb3/
I would do something like this:
// Global forces
character.vy += gravity;
// User input
if (keydown.up) {
character.vy += -2;
}
// Final location
if (character.y + character.vy >= 184) {
// Update player location.
character.y += character.vy;
} else {
// Player was about to move past ground so place player directly on ground
// and reset velocity.
character.y = 184;
character.vy = 0;
}

Canvas collision JavaScript

I cannot figure out why my collision function is working for one element and not for another.It's madness ,please help.It detects the food collision but it doesn't detect when the head of the snake hits it's other elements.
window.onload= function ()
{
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var canvasWidth=window.innerWidth-20;
var canvasHeight=window.innerHeight-20;
canvas.width=canvasWidth;
canvas.height=canvasHeight;
var up=false;
var down=false;
var left=false;
var right=true;
var snake={
x:20,
y:0,
w:10,
h:10
};
var snakeBody=[];
for (i = 0; i < 20; i++) {
snakeBody.push({
x:snake.x ,
y:snake.y ,
w:snake.w,
h:snake.h
});
snake.x +=20;
}
var food={
x:Math.floor(Math.random() * (canvasWidth-50)),
y:Math.floor(Math.random() * (canvasHeight-50)),
w:10,
h:10
};
function moveUp()
{
snakeBody[0].y -=3;
}
function moveDown()
{
snakeBody[0].y +=3;
}
function moveLeft()
{
snakeBody[0].x -=3;
}
function moveRight()
{
snakeBody[0].x +=3;
}
function draw()
{
context.clearRect(0,0,canvasWidth,canvasHeight);
context.fillStyle="black";
context.beginPath();
for (var i = snakeBody.length - 1; i > 0 ; i--) {
context.rect(snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h);
snakeBody[i].x = snakeBody[i-1].x;
snakeBody[i].y = snakeBody[i-1].y;
}
context.rect(snakeBody[0].x,snakeBody[0].y,snakeBody[0].w,snakeBody[0].h);
context.rect(food.x,food.y,food.w,food.h);
context.stroke();
context.fill();
for (var i = 1; i < snakeBody.length; i++) {
if (intersects(food.x,food.y,food.w,food.h,snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h)) {
generateFood();
growSnake();
}
var head=snakeBody[0];
if (intersects(head.x,head.y,head.w,head.h,
snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h)) {
alert('game over');
}
}
directions();
collision();
update();
}
function growSnake()
{
for (i = 0; i < 5; i++) {
snakeBody.push({
x:snake.x ,
y:snake.y ,
w:snake.w,
h:snake.h
});
snake.x +=20;
}
}
function generateFood()
{
food.x=Math.floor(Math.random() * (canvasWidth-50));
food.y=Math.floor(Math.random() * (canvasHeight-50));
}
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
w2 += x2;
w1 += x1;
if (x2 > w1 || x1 > w2) return false;
h2 += y2;
h1 += y1;
if (y2 > h1 || y1 > h2) return false;
return true;
}
function directions()
{
document.onkeydown = function(e)
{
var event = window.event ? window.event : e;
var keycode = event.keyCode;
if (keycode===37 && right===false) {
left=true;
right=false;
up=false;
down=false;
}
if (keycode===38 && down===false) {
up=true;
down=false;
left=false;
right=false;
}
if (keycode===39 && left===false) {
right=true;
left=false;
up=false;
down=false;
}
if (keycode===40 && up===false) {
down=true;
up=false;
left=false;
right=false;
}
};
}
function update()
{
if (up) {moveUp();}
if (down) {moveDown();}
if (left) {moveLeft();}
if (right) {moveRight();}
}
function gameOver()
{
alert('game over!');
}
function collision()
{
if (snakeBody[0].x >canvasWidth) {
snakeBody[0].x = 0;
}
if (snakeBody[0].x < 0) {
snakeBody[0].x=canvasWidth;
}
if (snakeBody[0].y>canvasHeight) {
snakeBody[0].y=0;
}
if (snakeBody[0].y <0) {
snakeBody[0].y=canvasHeight;
}
}
setInterval(draw,20);
};
It's a lot of code, so here's a fiddle http://jsfiddle.net/5nLQG/
Focus would seem to be function intersects:
function intersects(x1, y1, w1, h1, x2, y2, w2, h2) {
w2 += x2;
w1 += x1;
if (x2 > w1 || x1 > w2) return false;
h2 += y2;
h1 += y1;
if (y2 > h1 || y1 > h2) return false;
return true;
}
Yep. Check it out. Game over is being hit. Repeatedly. Because your blocks are all scrunched up it's difficult to do collision detection in the first place. In fact only checking after the 20th cube was I able to have a functional game. Check it out
if (i - 20 > 0&& intersects(snakeBody[0].x,snakeBody[0].y,snakeBody[0].w,snakeBody[0].h,
snakeBody[i].x,snakeBody[i].y,snakeBody[i].w,snakeBody[i].h)) {
clearInterval(pulse);
}
Where I declare pulse the timeInterval ID
http://jsfiddle.net/fC25X/
I would work on spacing your cubes and you should be golden
What to do?
I think there's a great joy in figuring out these simple games for yourself. For instance minesweeper if not done properly can give massive stackoverflows. I've written a snake game before and I will quickly explain how I managed cubes following each other. Your way seems like it could work with a bit of playing around, so only read further if you don't care about figuring out the process yourself. My way is probably not best either.
Actually pretty terrible
I remember my particular implementation of snake I kept a separate array called 'turningPoints' and on keypress it looked something like this:
document.onkeydown = function(e)
{
var event = window.event ? window.event : e;
var keycode = event.keyCode;
if (keycode===37 && right===false) {
left=true;
right=false;
up=false;
down=false;
turningPoints.push(snake[0].x,snake[0].y,[1,0]); // [1,0] matrix for right
}
}
Then when iterating over each cube (this is where it gets messier) I moved each cube in the direction it was going, and then checked to see if it had reached a turningPoint (with some margin of error), if it had then it would change direction:
if(snake[i].x == turningPoint[j].x && snake[i].y == turningPoint[j].y)
snake[i].direction = turningPoint[j].direction;
I made sure to clean up turningPoints (after all the cubes have followed the instruction there's no need to keep the point), and the whole thing worked OK
BUT
I got bored, and played around with your way a bit more and came up with this http://jsfiddle.net/LAMZt/ It's quiet a bit different, but it's more or less the same. Noticed another issue was that you snake's head was the left most piece going right, so naturally, it collided with the other pieces. So I fixed it by rendering additional pieces as the snake moved. The rest was just house keeping so I could save it as a gist (referenced this question of course).

Making an image jump up (and fall back)

I am making a platform game in JavaScript and I need some help.
How do I make an image jump up 50px in JavaScript when the spacebar pushed then fall back to a certain position?
If you mean jumping as in jumping with gravity - you'd need a parabola formula.
E.g.: http://jsfiddle.net/pimvdb/7JFU3/.
var x = 0;
var interval = setInterval(function() {
x++;
image.style.top = 50 - (-0.1 * x * (x - 50)) + 'px';
if(x >= 50) clearInterval(interval);
}, 20);
I'm working on exact the same thing. Here's my github project link https://github.com/beothorn/webcomicsgame
Look at MainCharacter.js at
if(gameCommandState.up){
if(this.canJump(game))
this.element.yAccelerate(-this.yAcceleration);
}
You can fork it if you want, but I'm doing it using canvas.
We had fun extending this to have an image keep bouncing up and down
var x = 0;
var goingUp = true;
var interval = setInterval(function() {
if(goingUp==true) {
x++;
if(x >= 50) {
goingUp=false;
//alert("go down")
}
} else {
x--;
if(x <= -50) {
goingUp=true;
//alert("go up")
}
}
$('#demo').css('top', 50 - (-0.1 * x * (x - 50)));
}, 20);

Categories