How to make an object move on any direction? - java

I have a gun sprite that rotates 360 degrees,I wan't it to fire bullets on any direction, how do I do that? I can't just increment the x,y coordinates of the bullet cause it will just go up,down,left and right.
EDIT:
The bullet movement seems only to rotate but not going anywhere or outside the screen
bulletPosition.x=MathUtils.cosDeg(cannonObj.cannonAngle())*2;
bulletPosition.y=MathUtils.sinDeg(cannonObj.cannonAngle())*2;
bulletVelocity.x=MathUtils.cosDeg(cannonObj.cannonAngle())*10;
bulletVelocity.y=MathUtils.sinDeg(cannonObj.cannonAngle())*10;
bulletPosition.x+=bulletVelocity.x*deltaTime;
bulletPosition.y+=bulletVelocity.y*deltaTime;
//spawning bullets
public void draw(SpriteBatch batch){
bulletIterator=bullets.iterator();
while(bulletIterator.hasNext()){
Sprite sprite=bulletIterator.next();
sprite.draw(batch);
sprite.setPosition(bulletPosition.x,bulletPosition.y);
}

Vector gunPos; // the gun position,dah
Vector bulletPos; //the bullet position
Vector bulletVelocity; //need explanation?
float gunAngle; //the rotation of the gun in degrees
float distanceFromCenter=gunSize.x/2; //the distance from the gun center you want the bullet to appear
bulletPos.x=MathUtils.cosDeg((gunAngle)) * distanceFromCenter;
bulletPos.y=MathUtils.cosDeg((gunAngle)) * distanceFromCenter;
bulletPos.plus(gunPos);
bulletVelocity.x=MathUtils.cosDeg((gunAngle)) * bulletSpeed;
bulletVelocity.y=MathUtils.cosDeg((gunAngle)) * bulletSpeed;

Related

Box2D rotate a body around its center.. LIBGDX

Im trying to rotate a body around its center in box2d. The rotation of the sprite works, but what the body does is rotate around its top left point.
Code for rotating the sprite:
public void drawBitMap(Bitmap bit, float x, float y, float width, float height, float rotation){
Sprite sprt = null;
if (!sprts.containsKey(bit)) {
sprt = new Sprite(bit.texture);
sprts.put(bit, sprt);
}else{
sprt = sprts.get(bit);
}
sprt.setOrigin(width/2,height/2);
sprt.setRotation(rotation);
sprt.setPosition(x,y);
sprt.setSize(width,height);
sprt.draw(this);
}
Code for rotating body:
body.setTransform(x, y, rotation * MathUtils.degreesToRadians);
Images of what is happening:
It probably has something to do with the definition of the origin of the body or fixture. Can you show me the code you used to create the body and fixture?
EDITED
Ok, I've checked your JSON and it's exactly what I thought. In those JSONs the fixture was defined with the center of the body at its bottom left corner.
The point (0,0) is the center of the body, and the fixture you are defining has that point at its bottom left corner, that's why it rotates around its bottom left corner.
This might sound confusing so I'm going to give you a simple example: a square.
A square of size 1 that has this same problem would have its vertices defined at (0,1), (1,1), (1,0) and (0,0).
As stated above, the point(0,0) is the center of the body so, in order to alineate the centers of the fixture and body, the vertices should be defined AROUND the point that is the center of the body(0,0).
The correct square would have the following vertices: (-0.5,0.5), (0.5,0.5), (0.5,-0.5), (-0.5,-0.5).

How to center a hitbox inside rotating triangle sprite?

I'm having problems plotting hitboxes in the center of rotating triangle sprites. When I spawn the triangles, I set the collision rectangle like this:
bullet.collisionRect.width = flashingTriangleSprite.getWidth() - 20;
bullet.collisionRect.height = flashingTriangleSprite.getHeight() - 14;
bullet.scale = 0.287f;
Updating is done as follows:
bullet.position.y += bullet.velocity.y;
// center collision rect over triangle sprite
bullet.collisionRect.x =
bullet.position.x + ((flashingTriangleSprite.getWidth() / 2) - bullet.collisionRect.getWidth() / 2);
bullet.collisionRect.y =
bullet.position.y + ((flashingTriangleSprite.getHeight() / 2) - bullet.collisionRect.getHeight() / 2);
if (bullet.scale < 1)
{
bullet.scale += 0.011f;
}
if (bullet.driftDirection == Globals.Direction.LEFT)
{
bullet.rotation -= 3.804f;
bullet.position.x -= bullet.velocity.x;
}
else // drift right
{
bullet.rotation += 3.804f;
bullet.position.x += bullet.velocity.x;
}
This is the result: http://imgur.com/rIvIT8K
As you can see, the hitboxes are not centered. In fact, the hitboxes seem to change position within the triangle sprites depending on the rotation of the triangle sprite. Any ideas what I'm doing wrong?
When determining your hitbox centre position you are targeting the centre of the triangle sprite (a square), but that is not the perfect centre of the drawn triangle.
Therefore your hitbox is always closer to one of the vertices of the triangle (depending on the rotation). Also, your hitboxes are never rotated with the triangle, instead they always appear to be standing vertically.
To place the hitbox in the middle of the triangle you should aim for 1/3 of the height of the sprite (if the triangle has one side flat at the bottom in the base sprite image) and when you are updating the sprite, attempt to update the hitbox rotation to match the sprite rotation.
You could also try making a more accurate triangle hitbox using the PolygonShape, but that's up to you.

How to make set sprite position based on degree?

I have a sprite arrow that rotates like a clock hand, I need my other sprite to spawn where the arrow is pointed.
//arrow rotation:
int x=Gdx.input.getX();
int y=Gdx.graphics.getHeight()-Gdx.input.getY();
double radians= Math.atan2(y - launcherSpr.getY(), x - arrowSpr.getX());
float angle=(float)radians*MathUtils.radiansToDegrees-85;
arrowSpr.setRotation(angle);
//The other sprite that is spawned whenever the method is called
public void newBullet(){
Sprite sprite=Pools.obtain(Sprite.class);
sprite.set(bulletSpr);
sprite.setPosition(300, 600);
bullets.add(sprite);
}
Right now when the method newBullet() is called, a bullet sprite will spawn and it's Y is translated by 5(going upward by 5 pixels per frame). What I want is that the bullet will spawn based on where the arrow is pointed and go upward or downward based on the situation.

Need help getting image to rotate to face the mouse in a top-down shooter (Java)

I am having trouble with the movement of the player in my game. The game is a top-down shooter in which the location of the player is controlled with W, A, S, and D. I want to control the direction the player faces by moving the mouse.
I know I need to use the mouseMoved method to track the mouse, but I am lost in both calculating the angle and actually rotating the image.
The image is basically a circle with black line to represent the gun sticking out.
Any help is greatly appreciated!
You can calculate the angle using the player and mouse coordinates:
float angle = (float)(Math.atan2(player.y - mouse.y, player.x - mouse.x));
this will give you the angle in radians.
Then when you are drawing the object:
AffineTransform reset = new AffineTransform();
reset.rotate(0, 0, 0);
Graphics2D g2 = (Graphics2D)g;
g2.rotate(angle, player.x, player.y);
//draw the image here
g2.setTransform(reset);

Java LWJGL - Vertical Shooting Bugs Out

So i've made my own FPS, graphics and guns and all of that cool stuff; When we fire, the bullet should take a random direction inside the crosshair, as defined by:
float randomX=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomY=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
bulletList.add(new Bullet(new float[]{playerXpos, playerYpos, playerZpos}, new float[]{playerXrot+randomX, playerYrot+randomY}, (float) 0.5));
We calculate the randomness in X and Y (say you had a crosshair size (guns[currentWeapon].currAcc) of 10, then the bullet could go 0.4 to any side and it would remain inside the crosshair.
After that is calculated, we send the player position as the starting position of the bullet, along with the direction it's meant to take (its the player's direction with that extra randomness), and finally it's speed (not important atm, tho).
Now, each frame, the bullets have to move, so for each bullet we call:
position[0] -= (float)Math.sin(direction[1]*piover180) * (float)Math.cos(direction[0]*piover180) * speed;
position[2] -= (float)Math.cos(direction[1]*piover180) * (float)Math.cos(direction[0]*piover180) * speed;
position[1] += (float)Math.sin(direction[0]*piover180) * speed;
So, for X and Z positions, the bullet moves according to the player's rotation on the Y and X axis (say you were looking horizontally into Z, 0 degrees on X and 0 on Y; X would move 0*1*speed and Z would move 1*1*speed).
For Y position, the bullet moves according to the rotation on X axis (varies between -90 and 90), meaning it stays at the same height if the player's looking horizontally or moves completely up if the player is looking vertically.
Now, the problem stands as follows:
If i shoot horizontally, everything works beautifully. Bullets spread around the cross hair, as seen in https://dl.dropbox.com/u/16387578/horiz.jpg
The thing is, if i start looking up, the bullets start concentrating around the center, and make this vertical line the further into the sky i look.
https://dl.dropbox.com/u/16387578/verti.jpg
The 1st image is around 40ยบ in the X axis, the 2nd is a little higher and the last is when i look vertically.
What am i doing wrong here? I designed this solution myself can im pretty sure im messing up somewhere, but i cant figure it out :/
Basicly the vertical offset calculation (float)Math.cos(direction[0]*piover180) was messing up the X and Z movement because they'd both get reduced to 0. The bullets would make a vertical line because they'd rotate on the X axis with the randomness. My solution was to add the randomness after that vertical offset calculation, so they still go left and right and up and down after you fire them.
I also had to add an extra random value otherwise you'd just draw a diagonal line or a cross.
float randomX=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomY=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
float randomZ=(float)Math.random()*(0.08f*guns[currentWeapon].currAcc)-(0.04f*guns[currentWeapon].currAcc);
bulletList.add(new Bullet(new float[]{playerXpos, playerYpos, playerZpos}, new float[]{playerXrot, playerYrot}, new float[]{randomX,randomY, randomZ},(float) 0.5));
And the moving code...
vector[0]= -((float)Math.sin(dir[1]*piover180) * (float)Math.cos(dir[0]*piover180)+(float)Math.sin(random[1]*piover180)) * speed;
vector[1]= ((float)Math.sin(dir[0]*piover180)+(float)Math.sin(random[0]*piover180)) * speed;
vector[2]= -((float)Math.cos(dir[1]*piover180) * (float)Math.cos(dir[0]*piover180)+(float)Math.sin(random[2]*piover180)) * speed;
You didn't need to bust out any complex math, your problem was that when you were rotating the bullet around the y axis for gun spread, if you were looking directly up (that is, through the y axis, the bullet is being rotated around the path which its going, which means no rotation whatsoever (imagine the difference between sticking your arm out forwards towards a wall and spinning in a circle, and sticking you arm out towards the sky and spinning in a circle. Notice that your hand doesn't move at all when pointed towards the sky (the y-axis)) and so you get those "diagonal" bullet spreads.
The trick is to do the bullet spread before rotating by the direction the player is looking in, because that way you know that when you are rotating for spread, that the vector is guaranteed to be perpendicular to the x and y axes.
this.vel = new THREE.Vector3(0,0,-1);
var angle = Math.random() * Math.PI * 2;
var mag = Math.random() * this.gun.accuracy;
this.spread = new THREE.Vector2(Math.cos(angle) * mag,Math.sin(angle) * mag);
this.vel.applyAxisAngle(new THREE.Vector3(0,1,0),this.spread.y / 100); //rotate first when angle gaurenteed to be perpendicular to x and y axes
this.vel.applyAxisAngle(new THREE.Vector3(1,0,0),this.spread.x / 100);
this.vel.applyAxisAngle(new THREE.Vector3(1,0,0),player.looking.x); //then add player looking direction
this.vel.applyAxisAngle(new THREE.Vector3(0,1,0),player.looking.y);
this.offset = this.vel.clone()
I don't use java but I hope you get the main idea of what im doing by this javascript. I am rotating a vector going in the negative z direction (default direction of camera) by the spread.y, and spread.x, and then I am rotating by the pitch and yaw of the angle at which the player is facing.

Categories

Resources