im a programming beginner and i have do to for a game we are coding a shotgun shot but have a problem and dont know how to do it
i want to add a bullet in the game that when you shoot it, it spits itself into a few and small bullets in small different directions, so basically a shotgun shot.
i already have a normal bullet with his position,vector and velocity , and you can shoot it already. but my problem is or the thing i dont understand is how i can split that one bullet after i shoot it in many bullets and how every of it gets it own position and moving vector
Bullet class{
Vector2 moveVector;
float speed =15;
public void setMoveVector(float x, float y) {
moveVector = new Vector2(x,y);}
// in that area here its for the bullet how it moving/acting including if the path is free or blocked by walls or something
if(map.pathFree(getX(), getY(), getX()+ moveVector.x * speed, getY() + moveVector.y * speed, this)) {
setPosition(getX() + moveVector.x * speed, getY() + moveVector.y * speed);
//somewhere here sould come the code splitting the bullet
//removing the bullet after a distance
DistanceIndex += speed;
if(DistanceIndex >= 1000) {
remove();
}
}
else
HitWall();
if(outsideMap()) this.remove();
}
....
}
Obj Class
//class/object/gamefigure using/creating the bullet
.....
public void shootingMethod(){
......
double direction_x = Math.cos(Math.toRadians(rotation));
double direction_y = Math.sin(Math.toRadians(rotation));
Bullet bullet = new Bullet();
....
bullet.setMoveVector((float)direction_x, (float)directoin_y);
}
Picture of my problem i mean
Just make a bunch of smaller bullets start off at the same position and travel in slightly different directions. You could rotate the velocity vectors slightly for each bullet to achieve this. If they aren't already, you can make the bullets sensors so overlapping is not a problem
Related
I am making a game like pong except that there is only one paddle and the ball moves in projectile motion. The goal is to keep the ball bouncing on your paddle for as long as possible. I when I have the ball hit the paddle the direction of the y component of the velocity has it's sign flipped. The issue with this is that when the ball is moving up gravity acts upon in in that direction, speeding it up. The code is below
This is the code for my ball class, this is the tick method which is called 60 times a second
public Ball(double x, double y, Game game) {
super(x,y);
this.game=game;
}
public void tick() {
time+=1.0/60.0;
if(x<=0)
xreflection=1.0;
else if(x>=Game.Width-15)
xreflection=-1.0;
if(y<=0)
yreflection=1.0;
else if(y>=Game.Height-15)
gameover=1;//different variable here as I use this to end the game if the ball hits the bottom of the screen
x+=traj.xvel()*xreflection;
y-=traj.yvel(time)*yreflection;
if(Physics.Collision(this, game.getP())) {
time=2;
System.out.println("Collision");
yreflection=-1;
}
}
This is my ball Trajectory class which handles all the math for this
public double xvel() {
double xvelo=initvel*Math.cos(Math.toRadians(theta));
return xvelo;
}
public double yvel(double time) {
double yvelo;
yvelo=initvel*Math.sin(Math.toRadians(theta))-(9.8*time);
return yvelo;
}
And I have tried to use an if statement with y reflection to make 9.8 negative when yreflection is 1 and positive when it is -1.
you are not really doing reflection ... to reflect by major axis you should negate the appropriate coordinate of the speed vector (and correct the position) I do not see such behavior in your code. Instead your y velocity has no sign regardless of the direction up/down hence you just add gravity acc to it ... to remedy either rewrite the code or add the yreflection to your gravity related code too... also you got theta? I would expect angle only in the first shooting
see
Bouncing Ball Making it slow down at peak of height
My Algorithm to Calculate Position of Smartphone - GPS and Sensors
pendulum simulation
You just use/add forces you want to use. But in your collision once you detect you are inside wall you need to correct the position along with the reflection of speed too otherwise you risk double collisions ...
Here small C++ example with air friction:
//---------------------------------------------------------------------------
double pos[2],vel[2],acc[2],r; // ball
double x0,y0,x1,y1; // walls
//---------------------------------------------------------------------------
void ball_update(double dt)
{
int i;
double v,k=0.0001,g=9.81;
dt*=10.0; // time multiplier for simulation speed ...
// compute driving force/acceleration
v=sqrt((vel[0]*vel[0])+(vel[1]*vel[1])); // |vel|
acc[0]= -(k*vel[0]*v); // gravity + air friction (k*vel^2)
acc[1]=+g-(k*vel[1]*v);
// Newton/D'Alembert simulation
for (i=0;i<2;i++) vel[i]+=acc[i]*dt;
for (i=0;i<2;i++) pos[i]+=vel[i]*dt;
// colision/reflect
if (pos[0]<x0+r){ pos[0]=x0+r; vel[0]=-vel[0]; }
if (pos[0]>x1-r){ pos[0]=x1-r; vel[0]=-vel[0]; }
if (pos[1]<y0+r){ pos[1]=y0+r; vel[1]=-vel[1]; }
if (pos[1]>y1-r){ pos[1]=y1-r; vel[1]=-vel[1]; }
}
//---------------------------------------------------------------------------
void ball_init()
{
Randomize();
pos[0]=0.5*(x0+x1);
pos[1]=0.5*(y0+y1);
double a=2.0*M_PI*Random(),v=50.0;
vel[0]=v*cos(a);
vel[1]=v*sin(a);
r=20.0;
}
//---------------------------------------------------------------------------
My coordinate system is (0,0) is top left and x point right and y points down ...
To use this just init the walls x0,y0,x1,y1 call the ball_init() and then in some timer call ball_update(dt) and render ball at pos and radius r ...
This is how it look like:
PS. You need to tweak the parameters like delta time dt, accelerations or add pixel scale to match your needs... You need to have all units compatible ... I recommend using SI (m,m/s,m/s^2,s,N,.. ) so you also need to decide how big is pixel (in meters)
I am programming a game of sorts which would be kinda long to explain, but in short the player is an ellipse() and follows the mouse around, whilst the rect() is the obstacle that moves down the screen and needs to be dodged by the player, otherwise it's game over. There are multiple rect as I am using an ArrayList to store each obstacle object.
Currently, the player can just pass straight through the rect without anything happening to it. I have tried to solve it multiple times but it got extremely messy and I couldn't understand much due to being extremely new to Java (only 1 week of experience), so I have just placed the empty code below.
tldr; I need to figure out how to get an ellipse/rect collision to work (in its own method). I only have 1 week of Processing/Java experience. I've cut out most of the code that you don't need to look at, mainly just kept the variables used to define the shapes and the code for the shapes just in case you need that. Also, if possible could the collision method could be placed inside the Enemy Class.
Enemy Class (all the variables used to define the rect)
class Enemy {
int enemyNumber; // used to determine enemy type
//VARIABLES FOR ENEMY
boolean redEnemy = false; // determine enemy colour
color enemyColour = color(#B9B9E8); // sets default colour to blue
PVector position, velocity;
float xDist, yDist; // x and y distance for Bar
float smallCircleRad, bigCircleRad; // radius for circles
// **************************************************************************
Enemy() { //CONSTRUCTOR
position = new PVector(width/2, random(-300000, -250));
//println(position.y);
velocity = new PVector(0, 10);
smallCircleRad = 200;
bigCircleRad = 400;
xDist = width;
yDist = 200;
enemyNumber = int(random(1, 6));
}
// **************************************************************************
void redBar(float xPos, float yPos, float xDist, float yDist) {
redEnemy = true;
noStroke();
enemyColour = color(#E38585);
fill(enemyColour);
rect(xPos, yPos, xDist, yDist);
}
void blueBar(float xPos, float yPos, float xDist, float yDist) {
redEnemy = false;
noStroke();
enemyColour = color(#B9B9E8);
fill(enemyColour);
rect(xPos, yPos, xDist, yDist);
}
Player Class (all the variables used to define the ellipse)
class Player {
int r = 50; //player radius
float playerX = width/2; //starting x coordinate
float playerY = height/2+500; //starting y coordinate
float speed = 20; //player speed
float angle; //angle used to calculate trajectory for player
void playerChar() { //method for player model and general rules
stroke(10);
rectMode(CENTER);
fill(playerColour);
ellipse(playerX, playerY, r*2, r*2);
}
Make your life easier by treating the player as a rectangle instead of a circle. You can still draw them as a circle, but for collision detection, use a rectangle. This is called a bounding box and is very popular in collision detection.
Then you can use rectangle-rectangle collision detection, which is much simpler.
Some basic google searches return these results:
Axis-Aligned Bounding Box
What is the fastest way to work out 2D bounding box intersection?
Processing Collision Detection
If for some reason you absolutely need the player to be a circle when calculating the collision, then I'd start by googling something like "circle rectangle collision detection".
If you still can't get it figured out, please post a MCVE in a new question and we'll go from there. Good luck.
I have a program where i create balls that bounce around. When two balls collide, both should split into two smaller balls, start moving in different directions.
This is how I handle collision
public boolean intersects (Ball b) {
double distance = Math.sqrt(Math.pow((this.x - b.x), 2) + Math.pow((this.y - b.y), 2));
if (this.size / 2 + b.size / 2 >= distance && !(this.equals(b))) {
return true;
} else return false;
I am looking for an idea, that will help to decide where to place smaller balls, so that they don't immediately collide again. I have tried different maneuvers but they all end up too close to each other so they all start splitting a bouncing and it become a chaos.
Here is the class Ball
public Ball(double x, double y, double size, double dx, double dy) {
this.x = x;
this.y = y;
this.size = size;
this.dx = dx;
this.dy = dy;
To move the balls I do the following
b.x = b.x + b.dx;
b.y = b.y + b.dy;
For the moment when the balls collide, i have two Ball Objects. I know the coordinates of their centers: x, y , speed dx with which they move along the x-axis and speed dy along the y-axis
I leave out the code that handles the view, cause I basically need a solution, how to change dx, dy, x and y for 4 balls, so that all of them move away from each other and do not immediately collide.
I don't really need code-solution , but rather a general idea.
I think you might have two problems. The first is that your four "new" balls are all starting at or near the point of collision, and your collision detector might immediately perceive them as colliding. To solve this, you could mark the "new" balls as unable to collide with each other for a pulse or two of your collision detector. I'd need to see the code to give a better solution.
Secondly, you'll probably want to randomize the result vector of the four "new" balls. Just set dx and dy randomly for each and that should be good enough.
So I can't seem to find an answer to this, but I am trying to fire bullets into a circle. I have a simple class for a circular path that I attach to a bullet and it reads from that class a position when given a time value. The bullet simply increments this time value, constantly updating its position to the next. This can be improved but until I get the logic down this is what I have. I know this method works because I tried it with a linear path. The problem is applying it to a circular path.
I want the bullet to circle around a point (say Point 'Center') with a given radius and speed. I want all bullets to travel at the same speed no matter the radius of the circle so a larger circle will take longer to complete than a shorter one. Currently what is happening is I have the CircularPath object giving saying x = r * cos(t) and y = r * sin (t) where t is in radians, but this is making a circle that increases in speed as the radius increases and the radius and center of this circle is completely off. The bullets are starting in the correct position, except the radius and speeds are off. I hope I am describing this adequately. I will post the code for anyone to inspect.
package io.shparki.tetris.go;
import io.shparki.tetris.util.Point2D;
import java.awt.Color;
import java.awt.Graphics2D;
public class CircularPath extends Path{
private double radius;
// Where Start is the center and end is the location of mouse
// Radius will be distance between the two
public CircularPath(Point2D start, Point2D end) {
super(start, end);
radius = normalToEnd.getLength();
color = Color.YELLOW;
}
public Point2D getPointAtTime(double time){
double px = start.getX() + radius * Math.cos(Math.toRadians(time));
double py = start.getY() - radius * Math.sin(Math.toRadians(time));
return new Point2D(px, py);
}
public double getFinalTime() { return 0; }
public CircularPath getClone() { return new CircularPath(start.getClone(), end.getClone()); }
public void update(){
super.update();
radius = normalToEnd.getLength();
}
public void render(Graphics2D g2d){
super.render(g2d);
g2d.drawLine((int)start.getX(), (int)start.getY(), (int)end.getX(), (int)end.getY());
//g2d.drawOval((int)(start.getX() - radius), (int)(start.getY() - radius), (int)radius * 2, (int)radius * 2);
}
}
x = r * cos(t/r)
y = r * sin(t/r)
The other solution is to model 2d momentum and impose a "gravitational force" toward the center point (or ellipsoidal focus, more generally) that you want the moving object to orbit around.
(The classic Space Wars game was implemented on a machine too slow to handle the trig computations in realtime, so they precomputed a 2d array each for the x and y components of the gravity field; they could then just do a table lookup based on the ship's last position and use that to update its momentum, which was then used to update its position. Slower machines forced more clever solutions.)
Hello everyone ,
I am developing a game where two points, one is A, and the other is B , the point A is a cannon and the other is the point where there is a touch of the user.
how can I do to get the line , say infinite to proceed with the bullet starting from point A ?
My math skills are a bit scarce : /
Someone who can recommend a way to do it with libgdx / java ?
You need the vector position of B minus the vector position of A, which will give the vector pointing from A to B. Try having a read through this, a basic knowledge of vectors is indispensible if you are going to be making games
To represent state, you can use something like following.
public class Bullet extends Actor {
private Vector2 position;
private Vector2 velocity;
public Bullet(Vector2 position, Vector2 velocity) {
this.position = position;
this.velocity = velocity;
}
#Override
public void act(float delta) {
super.act(delta);
// Since newPosition = oldPosition + velocity * time elapsed
this.position.mulAdd(this.velocity, delta / 1000);
}
// Override draw method to handle rendering.
}
Now, you can initialize a new Bullet at each touch event (or whenever you wish)
Bullet createBullet(Vector2 canonPosition, Vector2 touchPosition) {
return new Bullet(canonPosition.cpy(), //Initial position of bullet.
touchPosition.sub(canonPosition).nor()); // Velocity
}
Now just add the Bullet to the stage and have fun.
Hope this helps.
Good luck.