LibGDX - Best way to adjust fire rate in a loop - java

I'm making a 2D platformer / shooter with LibGDX. I'm having this loop where holding fire-button down causes bullets to fly from the main character's gun the whole duration while the fire-button is pressed down (rapid fire). That part works perfectly and as intended. However, I'd like the rate of fire to be a bit slower. Currently the loop just adds a bullet to the world on each game frame which means the rate of fire is ridiculously high.
I've been trying to find a good way to do this, to no avail. Any suggestions would be vastly appreciated.
the loop:
if (keys.get(Keys.FIRE)) {
player.setState(State.FIRING);
world.addBullet(new Bullet(1f,1f,0));
}

You can use a delay mechanism by having a variable which counts down the time and every time it hits 0, you make one shot and reset the time, for example to 0.2f when you want the player to shoot every 0.2s:
private float fireDelay;
public void render(float deltaTime) {
fireDelay -= deltaTime;
if (keys.get(Keys.FIRE)) {
player.setState(State.FIRING);
if (fireDelay <= 0) {
world.addBullet(new Bullet(1f,1f,0));
fireDelay += 0.2;
}
}
}

Use a constant to hold the fire rate and add a timing mechanism, like so:
public static final long FIRE_RATE = 200000000L;
public long lastShot;
if(System.nanoTime() - lastShot >= FIRE_RATE) {
world.addBullet(new Bullet(1f,1f,0));
lastShot = System.nanoTime();
}

I have seen #noone s answer and it is correct. I just answer you, because i had to add the same to my game. What i did: I had a variable boolean attacking, which stores if you are holding firebutton. Then i had 2 more variables: float bps, which stores how many bullets you can shoot per second and float reloadTime, which stores how long it takes to reload an empty magazin, if you use one. I also store a long time and a boolean reloading. Time stores the TimeUtils.millis() of your last shot, the reloading stores if you are reloading the magazin or just shooting. Then in the attack method i call a method: public boolean readyToAttack(), in which i compare TimeUtils.millis() to my variable time. If reloading = true, TimeUtils.millis() - reloadTime has to bigger then time. If not, TimeUtils.millis() - (1000 / bps) has to be bigger then time. If this is the case the method returns true and i can shoot. Noones solution is simpler, but for me bps is easier to understand so i used this.
Hope it helps

Related

Delta time not being calculated properly

I am trying to create a game in which objects spawn on a timer then start moving. I would like to keep the frame rate independent of the game speed, so I have tried to implement delta time:
lastTime = thisTime;
thisTime = (int) SystemClock.currentThreadTimeMillis();
deltaTime = thisTime - lastTime;
for (int i = 0;i < objectList.size();i++) {
objectList.get(i).updatePosition(deltaTime);
objectList.get(i).display(bitmapCanvas);
}
And my updatePosition method:
public void updatePosition(float deltaTime) {
this.y += 10/1000 * deltaTime;
}
From my understanding, the rate (10 in this case) should be divided by 1000 since deltaTime is in milliseconds, but I have tried it with various other values as well, and the objects just spawn on the screen and do not move. I had no issues making them move before trying to implement interpolation.
If it helps any, I was logging the delta time and it was usually around 20/30. Is this normal?
I have looked at probably 5 or 6 questions on GameDev and a couple on Stack Overflow but I think I must be misunderstanding something as I cannot get this to work.
So this doesn't appear unanswered, Jon Skeet was (obviously) correct:
The calculation of 10/1000 is being performing (at compile time) in integer arithmetic, so it's 0... Try 10/1000f, or just 0.01f.

Gravity in a Java ball bouncing program that refreshes every game tick

Hey I am trying to figure out the best way to implement gravity in my program that is simply a ball bouncing. The program uses a method that is called 50 times a second (the rate at which the gametimer ticks) and in this method I call the gravity method. In the gravity method I currently have
public void Gravity(){
this.currentPositionY = this.currentPositionY + 9;
if (this.currentPositionY >= 581){
this.currentPositionY=581;
}
}
Problems with my code: In gravity velocity is not constant it varies with the time, but I am unsure of how to implement time with the gravity method being called so often. Also currently I have it so that the ball stops at 581, so that it does not fall through the screen. How would I implement a bounce that is higher when the ball falls for longer and shorter when the ball falls less? Thanks for your time!
Have a variable outside of the method for its y-velocity. Every tick, increase its velocity accounting for gravity.
If the ball is past a boundary, set it to the boundary and set the velocity to -1*velocity to make it "bounce" in the other direction.
Maybe something like this:
private int currentVelocityY = 0;
private int gravity = 3;
public void Gravity(){
this.currentPositionY = this.currentPositionY + this.currentVelocityY;
if (this.currentPositionY >= 581){
this.currentPositionY=581;
this.currentVelocityY = -1 * this.currentVelocityY;
}
currentVelocityY = currentVelocityY + gravity;
}

tween movement speed control

I'm using tween engine for smoothing paths of moving entities. To make interpolation you feed function like this:
Tween.to(myObject, POSITION, 1.0f)
.target(50, 70)
.ease(Quad.INOUT)
.start(myManager);
Last argument of to() function is duration. What i learned, if path is longer, the entities move quicker to the target. Shorter the path is, entities move slower. I have float variable called movementSpeed, in every entity, that should move entities 7 pixels per seconds. What is the way using my variable for tween's movement speed instead of having it specified once at factory constructor?
My implementation:
Stack<Vector2i> stack = new Stack<Vector2i>();
/* ...pushing path points from last to first to the stack. */
Tween t = Tween.to(this, EntityAccessor.POS, 4.0f);
for (int i = stack.size()-1; i >= 0; i--) {
Vector2i cur = stack.get(i);
if (i == 0) { // if point is last then
t.target(cur.getX(), cur.getY());
} else {
t.waypoint(cur.getX(), cur.getY());
}
}
t.ease(Quad.INOUT);
t.path(TweenPaths.catmullRom);
t.delay(0.5f);
t.start(game.tweenManager);
Once the tween is created and its duration set with the factory method Tween.to(...) I don't think there is a way to alter its duration. I would suggest using a velocity and updating it every frame to have the effect you want. Having a set velocity or calculating it every frame defeats the purpose of a tween anyway.
I stead of hard-coding the duration, you could calculate it.
i.e. you can always calculate distance to be traveled by using
distance = sqrt(dx*dx + dy*dy)
Now having both distance and speed, you can set the duration as distance/speed.
Hope this helps.

How to make a rendering loop run at a consistent rate?

I've written a program with moving animated sprites based on user input that all takes place in a while(true) loop. Up until now the only way I've been timing the loop is by having a sleep(20) at the end of each run through the loop. I have noticed this effects the physics of my sprites negatively because my formula for calculating gravity is velocity = velocity + GRAVITY * Elapsed-Time and because the loop isn't running at a consistent rate the effect of gravity is not consistent either. Is there a way to keep the loop running consistently or better way of timing it so it actually runs on a schedule?
First, determine how long you want your frames to last. If you want 30 fps, then you'll have
final long frameDuration = 1000 / 30;
Next, when you start rendering, store the time, like so
final long then = System.currentTimeMillis();
render(); // surely it's more than this but you get the idea
final long now = System.currentTimeMillis();
final long actualDuration = now - then;
final long sleepDuration = frameDuration - actualDuration;
if(sleepDuration > 0) {
sleep(sleepDuration);
} else {
throw new FrameTooLongException();
}
velocity = velocity + GRAVITY * Elapsed-Time
This should work regardless of whether your frame rate is constant or not. The trick is to measure elapsed time accurately & consistently. Measure elapsed time from some point in your loop to the same point in the next loop.

The Math of a Jump in a 2D game

I'm working in J2ME, I have my gameloop doing the following:
public void run() {
Graphics g = this.getGraphics();
while (running) {
long diff = System.currentTimeMillis() - lastLoop;
lastLoop = System.currentTimeMillis();
input();
this.level.doLogic();
render(g, diff);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
stop(e);
}
}
}
So it's just a basic gameloop, the doLogic() function calls for all the logic functions of the characters in the scene and render(g, diff) calls the animateChar function of every character on scene, following this, the animChar function in the Character class sets up everything in the screen as this:
protected void animChar(long diff) {
this.checkGravity();
this.move((int) ((diff * this.dx) / 1000), (int) ((diff * this.dy) / 1000));
if (this.acumFrame > this.framerate) {
this.nextFrame();
this.acumFrame = 0;
} else {
this.acumFrame += diff;
}
}
This ensures me that everything must to move according to the time that the machine takes to go from cycle to cycle (remember it's a phone, not a gaming rig). I'm sure it's not the most efficient way to achieve this behavior so I'm totally open for criticism of my programming skills in the comments, but here my problem: When I make I character jump, what I do is that I put his dy to a negative value, say -200 and I set the boolean jumping to true, that makes the character go up, and then I have this function called checkGravity() that ensure that everything that goes up has to go down, checkGravity also checks for the character being over platforms so I will strip it down a little for the sake of your time:
public void checkGravity() {
if (this.jumping) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 0) {
this.jumping = false;
this.falling = true;
}
this.dy = this.jumpSpeed;
}
if (this.falling) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 200) this.jumpSpeed = 200;
this.dy = this.jumpSpeed;
if (this.collidesWithPlatform()) {
this.falling = false;
this.standing = true;
this.jumping = false;
this.jumpSpeed = 0;
this.dy = this.jumpSpeed;
}
}
}
So, the problem is, that this function updates the dy regardless of the diff, making the characters fly like Superman in slow machines, and I have no idea how to implement the diff factor so that when a character is jumping, his speed decrement in a proportional way to the game speed. Can anyone help me fix this issue? Or give me pointers on how to make a 2D Jump in J2ME the right way.
Shouldn't you be adjusting the jumpSpeed based on the elapsed time? That is, perhaps the speed changes by -75/sec, so your diff should be a weight for the amount of change applied to the jumpSpeed.
So pass in diff to checkGrav and do something like... jumpSpeed += (diff * (rate_per_second)) / 1000;
(assuming diff in milliseconds)
(Ideally, this would make it just like real gravity :D)
Why not just scale all constants by diff?
By the way, I'm embarrassed to say this, but I worked on a commercial game where gravity was twice as strong on characters going down as going up. For some reason, people preferred this.
This seems to be more of a question about game design than the math of a jump. It is a common problem that in games running on different processors one game will be executed faster and on other games it will be executed slower (thus changing the entire speed of the game). I'm not sure what common practice is in games, but whenever I made home-brewed 2D games (they were fun to make) I would have the concept of a game-tick. On faster machines
long diff = System.currentTimeMillis() - lastLoop;
lastLoop = System.currentTimeMillis();
Would be lower. A wait time would be derived from the diff so that the game would run at the same speed on most machines. I would also have the render method in a separate thread so that the game speed isn't dependent on the graphics.
I can give a formula like this (I use it everywhere). The X is the parameter of it starting from zero and ending on the length of jump.
if you want someone to jump at some Height (H) and at some Length (L), then function of the jump will look like this (and it won't' be able to ever look different):
y = minus(power(x - Length of Jump divided by two) multiply by 4 and
multiply by Height of the jump) divide by power of Length and add
Height of jump in the very end.
y = -(x-l/2)(x-l/2)*4*h/(l*l) + h
And if you want the jumping object to land on something, then you can check every new X if it's approximately standing on a platform and if it is standing on something, then don't make it just stop, make it's Y position exactly equal to the Y of platform.
If you're using something like Flash or other base which has inverted y axis, then multiply the function output by -1;

Categories

Resources