Im trying to make a Vortex effect on a Circle Body that is a Sensor.
I've been looking for this and all examples i look for are in C++ or Objective C and i dont seem to translate them well.
when my objects collition, it calls beginContact(..) and it sets a flag so that i can call bodyToUpdate.applyForce(...);
public void beginContact(Contact contact) {
setColliding(true);
}
//updating collition every frame
public void act(){
if (colliding) {
ball.getBody().applyForce(....);
}
how to calculate the amount of force to apply every frame to make it a vortex?
Edit:
so i now have the object going straight to the center of the vortex, but no "spin"
public void act() {
if (colliding) {
ball.getBody().setLinearVelocity(0, 0);
ball.getBody().applyForce((portal.getBody().getPosition().x - ball.getBody().getPosition().x) * i,
(portal.getBody().getPosition().y - ball.getBody().getPosition().y) * i,
ball.getBody().getPosition().x, ball.getBody().getPosition().y, true);
i++;
} else
i = 10;
}
If by "spin" you mean that the falling object would move along a curve or a spiral, rather then changing the direction of movement immediately towards the black hole, there is an easy fix for that.
ball.getBody().setLinearVelocity(0, 0);
This completely stops the current movement of the body. I would start by removing that line. Also, for better realistic behaviour, you can follow the proper formula to compute attractive force, which goes something like this:
force = mass1 * mass2 * [some constant] / (distance ^ 2)
When you have the vector from your body towards the black hole (computed as black hole position - body position), the length of the vector is the distance, and after normalizing and multiplying by the force, you have the desired forceX and forceY force vector that needs to be applied to the body each update, as long as it stays in range of the hole.
However this formula will cause the force to grow to infinity as body moves closer to the hole, so you could try changing to linear conversion (closest = 1, farest = 0) if that causes any trouble.
force = mass1 * mass2 * [some constant] * ( (maxDistance - distance) / maxDistance )
You want to implement a tangential force with a magnitude that increases towards the center of the vortex.
Here's some pseudocode.
radialVector = objectPosition - vortexPosition;
tangentialVector = radialVector.perpendicularVector();
if (radialVector.length() < vortexRadius) {
// Swirl faster when near the center of the vortex.
// Max tangential force when distance from center is 0.
// Min tangential force when distance from center is vortexRadius.
forceMagnitude = map(radialVector.length(), vortexRadius, 0, minTangentialForce, maxTangentialForce);
force = forceMagnitude * tangentialVector.normalize();
object.applyForce(force);
}
Here's an image that shows the vector components:
To create a whirlpool effect there should be increasing radial (Fr) and tangential (Ft) forces as the object moves closer to the center.
Related
I am making a Tile based infinite world game (Similar to Notch's Minicraft) and i am trying to implement light. Here is the function i use:
The arguments it takes are the World itself, and the tiles position relative to world co-ordinates
public static Vector.Vector3f calculateLight(World w, int worldx, int worldy){
float tileLightValue = 0;
float totalLights = 0;
for(Light currentLight : BlockLighting.lights){ // for each light
float currentLightXWorldPosition = currentLight.x;
float currentLightYWorldPosition = currentLight.y;
float distanceBetweenPoints = Core.MathFunctions.getDistance(
worldx,worldy,
currentLightXWorldPosition, currentLightYWorldPosition
);
if(distanceBetweenPoints < currentLight.range){
tileLightValue += distanceBetweenPoints / 20.175f;
totalLights += 1;
}
}
float lig = Core.MathFunctions.fclamp(((tileLightValue * -2.4f) + (69.3f / 100)), 0 , 1);
if(totalLights > 0){
return new Vector.Vector3f(lig,lig,lig);
}else{
// If no lights, return 0 as to not change the ambient light.
return new Vector.Vector3f(0,0,0);
}
}
Calculations are then made by taking the light value of this function, and then adding it to the base lighting (ambient)
...
Core.MathFunctions.fclamp(daylight + light, 0, 1)
...
And produces the Intended result:
But When the lights intersect, i get this glitch :
So it has to be a mathematical issue. So im hoping someone could offer a solution to this issue or modify my code to send me in the correct direction, the best way to describe the function is:
Given a list of light points, and a position of a tile. Calculate the appropriate lighting for said tile in an infinite world, so that when it is added to the ambient lighting of the world it produces a Terraria like lighting effect.
Note the code showing the ambient light calculation (2nd code block) is more or less pseudo-code, the actual code uses the Vector3 for color calculation, and that works fine, just thought id strip it down to lessen confusion
Edit: Here is a JSFiddle using the exact same code, to illustrate the issue. So you can see it, and tinker with it!
Interactive JS Example
I have a rectangle array holding multiple objects, moving back and forth on X axis.
Iterator<Rectangle> iter = array.iterator();
while ( iter.hasNext() ) {
Rectangle obj = iter.next();
array.get(i).x += speed * Gdx.graphics.getDeltaTime() ;
if (obj.x + obj.width > 800 || obj.x < 0) {
speed = -speed;
}
}
When the speed gets bigger, you'll start noticing the first object in the array overlapping with the other objects and pushing them apart. How to fix that?
Basically each object has
Rectangle obj = new Rectangle();
obj.x = xpos;
obj.y = ypos;
obj.width = width;
obj.height = height;
xpos += width + 4;
And has a texture, image, a sqaure, a rectange, a triangle... And each object is generated at an X position xpos different than the other. All they do is keep moving on the X axis, from x=0 till 800 and back.
What happens is that when the first object gets to 0, it tries to increase its speed again and overlapping with other objects, and then time after time, all objects keep overlapping and get further apart from each other. I want the distance between the objects to stay constant at any speed.
From what you've commented, the questions appears to be "How can I make all these blocks move together, bouncing from one edge to another". The issue being that you're getting bouncing, but they stop acting as a group.
Firstly, if you want to treat them as a group - the simplest way is to consider them as one large bounding box containing lots of smaller (inconsequential) objects. Moving that as a single object from side to side will give you the behaviour you need.
That aside, the direct answer to your question is "you're changing the direction mid-way through iteration". So in any single tick, some objects have moved left and some have moved right - meaning they stop acting as a group.
How you organise it is up to you, but this is the basic idea you need:
// assume "speedForThisFrame" is a float defined outside this function
float speedForNextFrame = speedForThisFrame
// iterate through however you want
Iterator<Rectangle> iter = array.iterator();
while ( iter.hasNext() ) {
Rectangle obj = iter.next();
obj.x += speedForThisFrame * Gdx.graphics.getDeltaTime() ;
// if it's moved out of bounds, we will change direction NEXT fame
if (obj.x + obj.width > 800 || obj.x < 0) {
speedForNextFrame = -speedForThisFrame;
}
}
// now that all movement has finished, we update the speed
speedForThisFrame = speedForNextFrame
The key thing is everything must move by the same amount, in the same direction, every frame. Changing the speed mid-update will cause them to act independently.
Note, you will still have issues when your group is larger than the bounds - or when they go over the bounds in one frame and don't fully get back the next frame. These are separate issues though and can be asked in a separate question.
I think your problem is that, caused by variations in Gdx.graphics.getDeltaTime(), the rectangles exceed your 0/800 borders by different distances.
An example:
First step:
Rect #1 x=790
Rect #2 x=780
Speed=100, DeltaTime=0.11 => DeltaX=11
After this step, Rect#1 would be at 801, Rect#2 at 791, their distance is 10.
Next step:
DeltaTime=0.12 => DeltaX=12
After this step, Rect#1 is at 789, Rect#2 at 803, their distance is 14.
Your rectangles vary their distance because they travel different distances. A possible solution would be to really bounce at the borders. So you should not only invert the speed but also take the distance a rectangle exceeded the border and let it travel this distance in the opposite direction:
So Rect#1 at 790, moving 11 pixels rightwards, should not be at 801 in the end of the step but at 799 (moving 10 pixels to the right and one to the left).
I'm trying to make this thing:
When user press a key once, the sprite smoothly moves on some pixels. But it just "teleporting" to the position. Here is the code:
int co = 0;
Vector2 ppos=new Vector2(x,y);
if (Gdx.input.isKeyJustPressed(Keys.A)){
while (co < 33) {
batch.begin();
ppos.y += Gdx.graphics.getDeltaTime()*5;
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(Splayer, ppos.x, ppos.y); //Splayer is a sprite
batch.end();
co++;
out(co+"");
}
}
What am I doing wrong?
I will deconstuct your code:
while (co < 33) {
So this will loop 33 times since you have co = 0 and increment co each loop.
ppos.y += Gdx.graphics.getDeltaTime()*5;
You increment the y position by your framerate * 5. so something like 5 * 0.02 * 33 is happening which makes 3.3. Nothing wrong with that but it is kinda unconventional to use a loop for that. Since doing y = 5 * framerate * 33 would be the same, easier and faster.
It depends on what you want to end up with but basically "we" do something like this.
//Have position variable
private Vector2 position;
//Have a speed variable
private float speed;
//direction variable
private Vector2 direction;
//have a velocity variable (direction * speed)
private Vector2 velocity;
velocity should be direction * speed and the velocity can then be added each frame to the position. let's say we want to move up. The direction would be (0,1) (the direction should never exceed the length of 1, if it does then normalize the vector direction.nor(). This will make sure it is 1 long so multiplying this will results in the same speed in any direction.
direction = new Vector2(0,1);
//an easy way to make it go 45 degree up/right would be
direction = new Vector2(1,1);
direction.nor(); //normalized to 1 long.
//now we can make the velocity
velocity = direction.cpy().scl(speed); //we copy the vector first so we are not changing the direction vector.
//If you want to have this framerate independent
velocity = direction.cpy().scl(speed * Gdx.graphics.getDeltatime);
Now we just add velocity to position. Basic math (1, 1) + (0, 1) = (1 ,2). Yes that is how simple Vectors are. original pos (0, 0)plus direction multiplied by speed+ (0 * 10, 1 * 10) = (0, 10)`. So to add velocity to position in code:
position.add(velocity);
batch.draw(textures, position.x, position.y);
This would be my way of doing it, I find this very easy.
What you are doing wrong is generating a new Vector each game loop when you press "A". You should think twice about having the new keyword in your loop. It is better the change you vector or reset it since it the old one will be lost in memory and needs to be collected. One Vector will not get you into trouble but 1 Texture that needs manual disposing will, learn it the right way.
Other then that, why have a variable named ppos? Why not just position or patientPosition or palaeoanthropologyPosition or whatever the "p" stands for. You are only required to type it once in most IDE because intellisense will pick it up. So make your and others life easier by clearly defining variables.
you should use Scene2D for smooth movement.
Having the following display() -
float tranX , tranY , tranZ ;
public void display(GLAutoDrawable gLDrawable) {
final GL gl = gLDrawable.getGL();
gl.glLoadIdentity();
gl.glPushMatrix();
gl.glTranslatef(tranX ,tranY ,tranZ);
gl.glCallList(i);
gl.glPopMatrix();
tranX += 0.05;
tranY += 0.05;
tranZ += 0.05;
}
As you can see each display() calling the matrix of the object in gl.glCallList(i) saved and get coordinates change by gl.glTranslatef(tranX ,tranY ,tranZ) .
Suppose that at some stage I want to save this object at its current position (after gl.glTranslatef calling ) and start to translate it to another tranX , tranY , tranZ values .
How could I save this object position considering the above gl.glPushMatrix() and gl.glPopMatrix() ?
Push/pop matrices are there to accumulate complex matrix transformations that would otherwise be painful to do by hand. For storing and moving object positions, keeping variables as you have done is correct. To expand on that and, as you say start moving in another, add a directionX/y/Z. Eg, tranX += directionX etc. Then when you want to change direction, simply set directionX/Y/Z to a different value.
The speed will change depending on how fast your computer is though. You'll want to find the time since the last frame (or last call to display) and do something like this: transX += velocityX * deltaTime etc.
If you want to move an object from one point to another specific point, you want to look into key-framed interpolation. For example position = pointA * (1.0 - x) + pointB * x and make x move from 0 to 1 (x += speed * deltaTime). When x is above one, pointA becomes pointB and pointB is set to the next position in the list. Then subtract 1.0 from x and continue.
Assuming you're translating from the origin (and even if you're not) - it should be quite possible to save the position of the object relative to the origin in this case. You might use an object that stores the data in three fields (xPosition, yPosition, zPosition).
To translate the object later on, you would first translate to this position and then translate from there as needed.
I'm having a little problem with figuring something out (Obviously).
I'm creating a 2D Top-down mmorpg, and in this game I wish the player to move around a tiled map similar to the way the game Pokemon worked, if anyone has ever played it.
If you have not, picture this: I need to load various areas, constructing them from tiles which contain an image and a location (x, y) and objects (players, items) but the player can only see a portion of it at a time, namely a 20 by 15 tile-wide area, which can be 100s of tiles tall/wide. I want the "camera" to follow the player, keeping him in the center, unless the player reaches the edge of the loaded area.
I don't need code necessarily, just a design plan. I have no idea how to go about this kind of thing.
I was thinking of possibly splitting up the entire loaded area into 10x10 tile pieces, called "Blocks" and loading them, but I'm still not sure how to load pieces off screen and only show them when the player is in range.
The picture should describe it:
Any ideas?
My solution:
The way I solved this problem was through the wonderful world of JScrollPanes and JPanels.
I added a 3x3 block of JPanels inside of a JScrollPane, added a couple scrolling and "goto" methods for centering/moving the JScrollPane around, and voila, I had my camera.
While the answer I chose was a little more generic to people wanting to do 2d camera stuff, the way I did it actually helped me visualize what I was doing a little better since I actually had a physical "Camera" (JScrollPane) to move around my "World" (3x3 Grid of JPanels)
Just thought I would post this here in case anyone was googling for an answer and this came up. :)
For a 2D game, it's quite easy to figure out which tiles fall within a view rectangle, if the tiles are rectangular. Basically, picture a "viewport" rectangle inside the larger world rectangle. By dividing the view offsets by the tile sizes you can easily determine the starting tile, and then just render the tiles in that fit inside the view.
First off, you're working in three coordinate systems: view, world, and map. The view coordinates are essentially mouse offsets from the upper left corner of the view. World coordinates are pixels distances from the upper left corner of tile 0, 0. I'm assuming your world starts in the upper left corner. And map cooridnates are x, y indices into the map array.
You'll need to convert between these in order to do "fancy" things like scrolling, figuring out which tile is under the mouse, and drawing world objects at the correct coordinates in the view. So, you'll need some functions to convert between these systems:
// I haven't touched Java in years, but JavaScript should be easy enough to convey the point
var TileWidth = 40,
TileHeight = 40;
function View() {
this.viewOrigin = [0, 0]; // scroll offset
this.viewSize = [600, 400];
this.map = null;
this.worldSize = [0, 0];
}
View.prototype.viewToWorld = function(v, w) {
w[0] = v[0] + this.viewOrigin[0];
w[1] = v[1] + this.viewOrigin[1];
};
View.prototype.worldToMap = function(w, m) {
m[0] = Math.floor(w[0] / TileWidth);
m[1] = Math.floor(w[1] / TileHeight);
}
View.prototype.mapToWorld = function(m, w) {
w[0] = m[0] * TileWidth;
w[1] = m[1] * TileHeight;
};
View.prototype.worldToView = function(w, v) {
v[0] = w[0] - this.viewOrigin[0];
v[1] = w[1] - this.viewOrigin[1];
}
Armed with these functions we can now render the visible portion of the map...
View.prototype.draw = function() {
var mapStartPos = [0, 0],
worldStartPos = [0, 0],
viewStartPos = [0, 0];
mx, my, // map coordinates of current tile
vx, vy; // view coordinates of current tile
this.worldToMap(this.viewOrigin, mapStartPos); // which tile is closest to the view origin?
this.mapToWorld(mapStartPos, worldStartPos); // round world position to tile corner...
this.worldToView(worldStartPos, viewStartPos); // ... and then convert to view coordinates. this allows per-pixel scrolling
mx = mapStartPos[0];
my = mapStartPos[y];
for (vy = viewStartPos[1]; vy < this.viewSize[1]; vy += TileHeight) {
for (vx = viewStartPos[0]; vx < this.viewSize[0]; vy += TileWidth) {
var tile = this.map.get(mx++, my);
this.drawTile(tile, vx, vy);
}
mx = mapStartPos[0];
my++;
vy += TileHeight;
}
};
That should work. I didn't have time to put together a working demo webpage, but I hope you get the idea.
By changing viewOrigin you can scroll around. To get the world, and map coordinates under the mouse, use the viewToWorld and worldToMap functions.
If you're planning on an isometric view i.e. Diablo, then things get considerably trickier.
Good luck!
The way I would do such a thing is to keep a variable called cameraPosition or something. Then, in the draw method of all objects, use cameraPosition to offset the locations of everything.
For example: A rock is at [100,50], while the camera is at [75,75]. This means the rock should be drawn at [25,-25] (the result of [100,50] - [75,75]).
You might have to tweak this a bit to make it work (for example maybe you have to compensate for window size). Note that you should also do a bit of culling - if something wants to be drawn at [2460,-830], you probably don't want to bother drawing it.
One approach is along the lines of double buffering ( Java Double Buffering ) and blitting ( http://download.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html ). There is even a design pattern associated with it ( http://www.javalobby.org/forums/thread.jspa?threadID=16867&tstart=0 ).