I looked up many threads on how to use delta time and I can't figure it out.
I want my guy to move at a constant speed every time I run the game.
So I have:
timer = new Timer(9, this);
timer.start();
then the paint method.
I tried doing start time at the beginning of the paint method and then a current time at the end of it. How would I make it affect the timer's speed or how far the player moves. I've tried multiplying the time delta by the increment to the x. nHeroX = dx*deltaTIme;
I feel like it's very simple I just need someone to tell me straight what to do please.
Traditionally, game programming relies on a continuous loop.
Anyway, all I have realized.
In this loop, you should separate model update and graphic update.
In your snipset, you seem to try mixing the two things.
In this loop :
- In a first time, you let the model to update.For example : guy's move from x to x1.
- In a second time, you must refresh the graphics to allow the guy to have a new position in the screen.
The speed of your guy depends on the guy model (ex: constant in your guy class).
But the speed of another type of guy could be different.
The general speed of your game relies on the FPS set in your main loop.
You can see an example on this post :
Java Main Game Loop
Good luck
Get the system time from the System object.
Get it again during your animation. Delta time is nothing more than subtraction.
Get rid of the JavaScript tag. The languages are completely different.
Related
I am in the extremely early stages of designing a game (so early that I haven't even committed to it yet). The idea is an RPG with a Quick Time Event for attacking and defending that relies on precise mouse movements or timed button presses to reduce damage taken or increase the damage of an attack (similar to Mario and Luigi or Paper Mario). I'm wondering the best way to go about programming a class that can handle this. Ultimately, I'd like to be able to write code such as this when I call the attack function, where all of the functionality of the QTE occurs in a single function call;
//Example code.
int attackPower = 23;
double qteSucessPercent = -1;
//more code
if(e.getSource == player.sword()) //when the player chooses to execute a sword attack.
{
qteSucessPercent = QTE.Jump();
if(qteSucessPercent< 0)
throw BadQTEException;
else if(qteSucessPercent>= .9)
player.attack(enemy[0], attackPower*2);
else if(qteSucessPercent>= .75)
player.attack(enemy[0], attackPower*1.5);
else if(qteSucessRate>= .5)
player.attack(enemy[0], attackPower);
else
System.out.println("Attack Failed");
}
This class needs to do several things.
It needs to be able to draw itself.
The QTE class needs to be able to handle key pressing or mouse motion events. I can handle the code for each type of QTE I wish to implement, but they need to be able to detect, on their own, where the mouse is and what buttons are being pressed.
Whatever it is drawing needs to delete itself once the QTE is over.
There will be multiple types of Quick Time Events. Each one will be drawn differently, have different victory conditions (one may require you to hit a sequence of buttons in the correct order, another may make you press a single button in rapid succession as many times as you can, ect), and modify the attack in various ways. The basic design of all QTEs is that they return a double value between 0 and 1, depending on how well the player did (generally, the higher the number, the better; if the attack returns 0, then the QTE received no input at all). In some situations, the QTE may be pass/fail, but the rest of the program is just watching for a non-0 number to be passed from the function call. For the sword, the attack's power is being modified by how well you do.
I know Swing isn't thread-safe (which, to my knowledge, means components won't update properly if you try to activate parts of their code from a thread other than the one you called them with, meaning I can't have two blocks of code executing at the same time if I want both sets of code to display animations), which is why I've written the code the way I have. The main thread gets to line 6, and executes QTE.Sword(). Until QTE.Sword() returns (which could be as long as five seconds), the rest of the program will freeze and not animate. I plan to use this to my advantage to achieve a bullet time effect, where the only thing animating is the QTE and the players and enemies remain stationary - though if I wanted an animation, like for a Mario and Luigi-like jump QTE, I'd set the player's sprite to be an animated gif that only plays once and only for as long as the QTE goes off.
Note that I am NOT ASKING FOR CODE. I'm asking for either pseudo-code or just a paragraph explanation of how I could program this. I think I can find a dead, open-sourced project on Github or Google Code and figure out the basics of the rest of the engine from there, but this is really the sticking point for me. Also, I am not asking for help handling mouse movements or keyboard presses. I have enough knowledge to code these on my own - I'm just not sure how to implement this in the context of an RPG. I know this isn't really stackoverflow's thing, and this question will probably get deleted, but I figure this is the best place to ask this sort of thing.
So, I'm creating a isometric game in JAVA; to put it simply, it has a map made of tiles, and when the user drag the mouse on the screen, the map moves. To give you guys an idea, it currently looks like this:
Before the actual prototype version, I built a small java application that had no "Game Loop" per se; the only thing updating the tile-map position was the event listeners for the mouse dragging, and it called the repaint() method after the movement update. It worked fine, and I could select Tiles and move the map without a problem.
Since then, I rebuild the prototype thinking in developing something more like a real game engine, with a Game States Manager and a real Game Loop; the Game Loop code looks like this:
init();
long start;
long elapsed;
long wait;
while(running){
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0)wait = 5;
try{
Thread.sleep(wait);
} catch(Exception e) {
e.printStackTrace();
}
}
A GameStateManager is acessed with the update() and draw() methods, so I can draw the map just fine, like the older prototype. The problem happened when I dragged the mouse on the screen so the map could move; the animation became VERY croppy, in the extent that I could actually see the black background between the tiles moving before the final position of all tiles.
At first I thought the problem was in a concurrency between the Game Loop thread and the event listeners of the main class, because the mouseDragged event could be called while the JPanel was trying to draw what the map was like a moment ago; then I tested this on my game loop code:
SwingUtilities.invokeLater(new Runnable(){
public void run(){
draw();
drawToScreen();
}
});
//draw();
//drawToScreen();
And now the prototype is working just fine.
So, my question is, is this performance heavy, or just a bad practice in Java? Also, was my "concurrency" assumption right? This is my first time dealing with threads in Java, so I don't really know if I dealed with the problem the right way.
obs: This is the entire class I made in which the game loop is in:
http://pastebin.com/RMRHYc5X
obs2: If someone is interested, the game loop logic I worked in was based on a youtube java tutorial made by pj644 named "2D Game Programming in Java".
obs3: Sorry if the question became too big, this is my first time posting a question on this site!
Swing isn't really a great technology for writing games, it updates slowly and is quite limited in a number of ways.
Having said that yes calling invokeLater or using a SwingWorker would be the correct way to update the screen when your game thread has done its work.
Before you go too much further though I really suggest looking at a 2d or 3d java graphics and game framework. You will be able to get much better results that way and a lot of the work in terms of setting up the game loop, updates, managing frame rates, etc will be done for you.
I just finished developing my mini-game on Android and I got some questions about perfomance and generally "how to": If I have 25+ objects on the creeen (just a polygon with 7-8 angles) its starts to lag hard and CPU usage is very high (15-20% without colision detection, up to 50% with collision detection on samsung note 10.1 tablet).
So I have ~25 polygons (asteroids) and they are always "flying". So to move them I make a Timer, right? On TimerTask I got something like this
public void move() {
translate[1] += speed[1];
translate[0] += speed[0];
updateTranslateMatrix(); // updating translate matrix and then send it into vertex shader
updateAABBCoords(); // update coordinates of Axis-aligned bounding box
updateCoordsByTranslate(); // update coordinates of verticles (to be able to define exact collision (with bullets and starship))
}
Is there something unnecessary in this method?
Also I want to ask if it is OK to run this timer every 17 ms? Or 17 ms is too often? I feel smoothness of movement only at 17 ms, may be I am doing it wrong? And same Timer interval I got on starship/bullets movement and on Collision detection.
Help me, please. I feel like missing something huge and fundamental, because 50% CPU on note 10.1 in that simple Asteroids game is not normal.
One key issue, I believe, is that you are assigning an individual Timer to every object instead of employing a general purpose game loop. A vast majority of games use a game loop which runs continuously and can be split, typically, into two components: Update and Render.
An article on basic game loop design for Java/Android
An answer to a relevant question on game loop design on gamedev.stackexchange.com
When using a game loop you can not guarantee being able to update exactly every 17ms or some other arbitrary duration. Instead, the Update and Render methods receive a DeltaTime parameter which is the time since the last frame.
This is then used when, for example, getting new object positions by multiplying it with the object's velocity. Doing so allows for smooth interpolation of position and ensures that object speed is not affected by CPU speed.
Basically I have a game where I want to play an explosion gif whenever the player (or an enemy) dies, but I want the gif to just play once.
I have everything set up in a class and I have an ArrayList that gets explosions added to it when I need it to, and I currently have it set up to remove them once the gif's duration has been reached (using System.currentTimeMillis()). The only problem there is that it isn't exact, and sometimes the gif stops early and disappears, and sometimes it rolls over, both situations causing the next one to start where the other one left off.
Is there some sort of method, class, listener of some sort, or anything I can use to tell what frame my gif is on, or how many times it has looped? My code can do the rest of the work, I just need something better to put in my if statement than this:
g2D.drawImage(explosion, x - 150, y - 150, null);
if(System.currentTimeMillis() - startingTime > 520){
System.out.println(System.currentTimeMillis());//for testing accuracy
Game.explosions.remove(this);
explosion = null;
}
The usual solution to this is to not use a gif :)
Most games will store each 'frame' of the gif separately, and display them in order, instead of trying to get gif rendering to work.
System.currentTimeMillis() is not terribly accurate, plus there can be tons of stuff going on in the background between calls to your draw function (all of which affects the framerate) so I would recommend against relying on that in general.
I was assigned to make an animated screensaver as a programming project for my Advanced Programming course. The objective is to have several moving components inside an undecorated, fullscreen frame, but I'm going step-by-step and doing it one component at a time.
Here's my source code so far:
http://pastebin.com/dc722188
Feel free to comment out any part involving file operations, they're not relevant for now.
Now, the issue I have here is that apparently the program recognizes my LogoComponet as encompassing the entire frame (even though it's not supposed to), and thus the conditions for collision are triggered immediately causing my logo object to suddenly start having seizures. I have no idea what's causing this at all, an even manually setting the bounds for the component won't work, and the fact that this is due tomorrow isn't helping my case at all.
So, uh, help, please? .___.
First, the code you pasted has the constructor named improperly in the twoSquareComponent. The problem is in your animate method. When you make your checks to change direction you change the direction, but the next call moves back to where you where. You need some way to track current direction.
As an example if you cross the side and your dx is 10 and current x is 11 you move to 1 and then the next animate call puts you back at 11, and then previous to 1, etc. It just repeats this hence the seizure effect you describe. I'll leave this to you as it's homework :) . but that is your problem You probably want to store current direction, and not change until you go out of bounds again.
Good Luck