I want to launch projectiles from the bottom-right corner of the screen towards the left side of the screen. Now, I want the projectiles to fly with random velocities and angles according to the screen dimensions, just like that. Now, I know this is very simple but from some reason I can't manage to make this work.
Here is what I have tried so far:
My first try - Launch function
private void launchProjectile() {
projectiles.peek().getBody().applyForce(projectiles.peek().getBody().getWorldVector(new Vector2(MathUtils.random(-20,-1*SCALAR_HEIGHT),
MathUtils.random(2*SCALAR_HEIGHT,8*SCALAR_HEIGHT)).scl(MathUtils.random(3*SCALAR_HEIGHT,5*SCALAR_HEIGHT))),
projectiles.peek().getBody().getWorldCenter(), true);
Gdx.app.log("System", String.valueOf(SCALAR_HEIGHT));
}
Here is my second try - Launch function
private void launchProjectile() {
float xVelocity;
float yVelocity;
xVelocity = (float) MathUtils.random(0,0)*SCALAR_WIDTH/2;
yVelocity = (float) MathUtils.random(20,20)*SCALAR_HEIGHT;
velocityProjectile.set(xVelocity,yVelocity); // Sets the velocity vector to the above values
velocityProjectile.sub(projectiles.peek().getBody().getPosition());
velocityProjectile.nor(); // Normalize the vector - Now it's fine and ready!
// Sets the start velocity of the projectile Trajectory to the current velocity
projectiles.peek().getBody().setLinearVelocity(velocityProjectile.scl(18+SCALAR_HEIGHT));
}
In both tries, the projectile flies way more than I need and it doens't take in consideration the screen size like it should.
Can you guys please tell me what is the right way to do this?
Thanks!!
Start with this page: http://www.iforce2d.net/b2dtut/projected-trajectory
In the "How fast should it be launched to reach a desired height?" section, you can see how much vertical velocity will be required to make the projectile reach the top of the screen. So you would pick a random number less than that, to make sure it doesn't go off the top of the screen.
Next, in the "How high will it go?" section, you can see the formula to find out how many time steps it will take for the projectile to reach maximum height. It will then take the same amount of time to come back down to the starting height. For example, let's say it would take 60 time steps to reach maximum height. That means it would take 120 time steps to fall down again to the same height as it started. Then you can set the horizontal part of the launch velocity so that it cannot go outside the screen in 120 time steps.
Related
Good evening. I am trying to smoothly move rectangle shape across the screen with glTranslatef. The concept is Windows 10 notifications. You know that they appear from right bottom of the screen, ease in-out animation and so on. I am trying to recreate it. But I dont know how can I achieve it.
Here is a basic requirement:
Move slowly, not in one frame. For example Windows 10 notifications. They move slowly, ease in-out (if possible).
I would appreciate any help, any tip, so thanks in advance!
You could start by finding the height (or width, as needed) define and initialize a variable (say, x) at half the height (again, or width) and move the notif x pixels up, divide x by 2, and raise the notif by 2 again, and repeat a number of times so that the notif doesn't take to long to appear, or look awkward, and finally move to the final desired position. (If you don't like how it looks, you can subtract x by 1 or some other number instead.)
I'm working with a game where you juggle a ball and to keep the ball in the air you need to apply forces to the ball.
I'm thinking if you touch right under the ball (180 degrees) and the maximum radius the more power you will kick away with the ball. So for an example if you touch the ball at 160 degrees and radius 6 you will be given less power than if you hit the ball at 170 degrees and radius 8,5.
How should I tackle it?
I would start by using several values:
Direction(int). on the right side direction is defined as 0, top 90,left 180,bottom 270; You can use it to describe an angle.
Force(double). a constant value to describe how much force is applied.
Point(int,int) to describe a point on your canvas.
~~~~~~~~~~~~~~~~~~~~~~~~~~
You can then add several useful calculations as:
int Distance(Point,Point): Math.hypot(x1-x2,y1-y2) [This is the source code giving the distance between two points]
The final movement can be done in several ways. I'd probably do it like this:
Per Tick:
Get current force. Add gravity force (9.81 in angle 270)
Per Click:
Take the position of the click and the position of the ball.
Calculate distance.
Calculate angle (Trigonometrics)
Finally calculate the force and add it.
How to add force?
Take angle.
Take "power".
Use more trigonometrics to calculate this.
I hope this helped you a bit. Sry for the format
I'm making a platformer game. The jumping and movement are working, and now I want to program the collisions. I have a sort of idea as to how this will work:
I wasn't sure whether this question should be here or in the game dev site.
I have two Vector2's - velo and momentum (velo is the velocity). Both are (0, 0). The momentum is what's added to the velocity each frame.
Each frame, I first get the input. Momentum is increased and/or increased based on the keys pressed (e.g: if (Gdx.input.isKeyPressed(Keys.A)) { momentum.x -= speed; })
I then multiply the momentum by 0.15. This is so that it slows down.
After this, I multiply the velocity by 0.8.
Then, I add the momentum to the velocity, to increase the velocity, as
this is what actually moves the player.
I then add the velocity to the position of the player.
To apply the gravity, I add a gravity vector (0, -10) to the position of the player.
So I need to find a way to move the player, but not allowing it to overlap any part of the world. The world is made up of lots of Rectangle instances. The player's body is also an instance of Rectangle. Would it be easier to rewrite the collisions using Box2D? What I've tried is checking if the player overlaps any rectangles when it's moved, and if it will, not moving it. But this doesn't seem to take everything into account - sometimes it works, but other times, it stops before touching the world.
TL;DR: I want to make collisions of my player with a world which is stored as a grid of rectangles. How would I do this, as my player is also a Rectangle. Would it be easier to use Box2D?
This answer gives a good overview about the details of collision detection:
https://gamedev.stackexchange.com/a/26506
However, that might be a bit overwhelming if you just want to get a simple game going. Does your game loop happen in fixed interval or is it dependent on the framerate? Maybe you could solve a part of your issue by simply dividing the collision detection into more steps. Instead of moving the full way during one update, you could make 10 little updates that each move you only a 10th of the distance. Then you do a collision check after each step, so it's less likely that you stop too early or move through thin objects.
That would of course be more taxing on the performance, but it's a naive and easy to implement approach to a solution.
EDIT:
Just wrap the position update in a for loop. I don't know how your code for collision checking and updating, but the general structure would be something like
for (int i = 0; i < 10; i++) {
newPosX += deltaX * 0.1; // 1/10th of the usual update
newPosY += deltaY * 0.1; // 1/10th of the usual update
if (checkCollision(newPosX, newPosY))
{
posX = newPosX;
posY = newPosY;
}
else
{
break; // We hit something, no more mini-updates necessary.
}
}
I'm creating android app, I'm going to build dialer, and spin the dialer. If the arrow intersect with the specific layer, it will pop out the result. I'm using sliced dialer into many layers, each layer represent different data and I have one arrow, pointing to the layer. This arrow is going to intersect with either one layer. I want to make the arrow calculate the percentage of overlapping among the layers so that the arrow can determine which it's pointing to. This is just my whole picture of doing it. Any suggestions or improvements ? BTW, how to calculate images overlapping percentage ?
I'd recommend keeping track the angle of the arrow and using that to calculate which section it is on. You should have the angle since you probably need it to draw the arrow. With the angle, it is quite simple to calculate which section it is on.
The code would look something like this:
public static final int TOTAL_DEGREES = 360;
public int calculateSelectedSection(float degrees, int numSections) {
return (int) (degrees / TOTAL_DEGREES * numSections);
}
I have a top down shooter using the paint method and I would like for it to work on all displays. It works by getting the resolution and dividing the x and y by 40 to separate it all up into squares.
My method of making the bullets move is by having a thread and a move method.
public void move(){
x += dx;
y += dy;
}
But if the persons computer is smaller, the bullet would move across the screen quicker. How can I get it to move at slower on smaller screens and faster on bigger screens?
Thank you for any suggestions.
What do you actually mean by slower? Do you mean as in the total time (measured in seconds) for the bullet to move across the screen is different in different devices?
Assuming that you did all calculation correctly as you described, I think you forgot one factor: different devices have different computing speed (and may be screen update speed also), so a "tick" in one device might be longer or shorted than some other. So when you call move, you should calculate how much time has passed from that last time moved() was called, and then you would calculate dx and dy based on it. Hope this make sense
I think you're forgetting not every computer runs at the same speed, if you've got this looping as fast as it can it will run very different on every computer. I suggest implementing delta scaling, this consists of timing the last frame, say you want 60fps, that means it needs to be 16 milliseconds, so take the time and divide it such as:
int lastframe = getFrameTime();
float scaler = lastFrame/(1000f/targetFrameRate)
then multiply all movements to this scale. such as:
public void move() {
x += dx * scaler;
y += dy * scaler;
}
A also see what you mean with different screen sizes being faster, this is because of the pixel density, to get this you will have to get the screen physical dimensions along with the resolution. For example if your screen is 20mm wide and its 1280x720, it's 20/1280 , this gives you the fact that each pixel is 0.015mm wide. You can then use the above scalar technique to scale them to move a physical world speed.