Firing a Bullet Towards Mouse when Mouse is Clicked - java

I'm creating a top-down dungeon game and I need to fire a bullet at the mouse location when the mouse is clicked. I know how to get the coordinates of the mouse, but I am unsure of how to fire a bullet towards that location when the mouse is clicked.
public void paint(Graphics g)
{//opens paint method
super.paint(g);//allows for painting and
g.drawImage(background, xBackground, yBackground, 1380, 720, this); //Background
myCharacter(x, y, g); //Character Sprite
spriteObjectX = x; //Sets the object x of the sprite equal to the 8 bit of the sprite
spriteObjectY = y; //Sets the object y of the sprite equal to the 8 bit of the sprite
sprite(g);
wallOne(g);
wallTwo(g);
wallThree(g);
wallFour(g);
wallOneTop(g);
wallOneBottom(g);
wallOneLeft(g);
wallOneRight(g);
wallTwoTop(g);
wallTwoBottom(g);
wallTwoLeft(g);
wallTwoRight(g);
wallThreeTop(g);
wallThreeBottom(g);
wallThreeLeft(g);
wallThreeRight(g);
wallFourTop(g);
wallFourBottom(g);
wallFourLeft(g);
wallFourRight(g);
//
sprite = new Rectangle(spriteObjectX, spriteObjectY, spriteObjectW, spriteObjectH);
//
wallOne = new Rectangle(wallOneX, wallOneY, wallOneW, wallOneH);
wallTwo = new Rectangle(wallTwoX, wallTwoY, wallTwoW, wallTwoH);
wallThree = new Rectangle(wallThreeX, wallThreeY, wallThreeW, wallThreeH);
wallFour = new Rectangle(wallFourX, wallFourY, wallFourW, wallFourH);
//
wallOneTop = new Rectangle(wallOneX, wallOneY, wallOneW, 1);
wallOneBottom = new Rectangle(wallOneX, (wallOneY + wallOneH), wallOneW, 1);
wallOneLeft = new Rectangle(wallOneX, wallOneY, 1, wallOneH);
wallOneRight = new Rectangle((wallOneX + wallOneW), wallOneY, 1, wallOneH);
wallTwoTop = new Rectangle(wallTwoX, wallTwoY, wallTwoW, 1);
wallTwoBottom = new Rectangle(wallTwoX, (wallTwoY + wallTwoH), wallTwoW, 1);
wallTwoLeft = new Rectangle(wallTwoX, wallOneY, 1, wallTwoH);
wallTwoRight = new Rectangle((wallTwoX + wallTwoW), wallTwoY, 1, wallTwoH);
wallThreeTop = new Rectangle(wallThreeX, wallThreeY, wallThreeW, 1);
wallThreeBottom = new Rectangle(wallThreeX, (wallThreeY + wallThreeH), wallThreeW, 1);
wallThreeLeft = new Rectangle(wallThreeX, wallThreeY, 1, wallThreeH);
wallThreeRight = new Rectangle((wallThreeX + wallThreeW), wallThreeY, 1, wallThreeH);
wallFourTop = new Rectangle(wallFourX, wallFourY, wallFourW, 1);
wallFourBottom = new Rectangle(wallFourX, (wallFourY + wallFourH), wallFourW, 1);
wallFourLeft = new Rectangle(wallFourX, wallFourY, 1, wallFourH);
wallFourRight = new Rectangle((wallFourX + wallFourW), wallFourY, 1, wallFourH);
mouseX = MouseInfo.getPointerInfo().getLocation().x; //Finding the x of the mouse
mouseY = MouseInfo.getPointerInfo().getLocation().y; //Finding the y of the mouse
g.setColor(Color.red);
g.drawLine(x + 90, y + 50, MouseInfo.getPointerInfo().getLocation().x - 8, MouseInfo.getPointerInfo().getLocation().y - 30); //Drawing a line from the player's gun to the mouse
repaint();//allows for repainting to look normal
}//close paint method
Here's my paint method

Here's how you calculate the trajectory from the bullet to the mouse.
Point get_trajectory(Point mouse,Point bullet){
return new Point(mouse.getX()-bullet.getX(),mouse.getY()-bullet.getY());
}
And in your game loop you should call this
void bullet_go_to(Point point){
Point trajectory=get_trajectory(mouseLocation,bullet);
bullet.x+=trajectory.getX();
bullet.y+=trajectory.getY();
}
You know how to find mouseLocation so in essence this is it.

Related

LibGDX's Model made with ModelBuilder not rendering

I'm learning to use LibGDX and my goal is to create a cube, with which you can control the resolution (number of vertices along each face). I already did that, and managed to use MeshBuilder to make it out of 6 different meshes and then render the resulting Mesh successfully using basic shaders :
Cube Mesh
//creates a square face with a normal vector and resolution number of vertices along any edge of the face
public Mesh createFace(Vector3 normal, int resolution) {
//creates 2 vectors perpendicular to each other and to the vector normal
Vector3 axisA = new Vector3(normal.y,normal.z,normal.x);
Vector3 axis = u.crs(normal, axisA);
Vector3 axisB = new Vector3(u.sqrt(axis.x),u.sqrt(axis.y),u.sqrt(axis.z));
//creates the arrays to hold the vertices and triangles
Vector3[] vertices = new Vector3[resolution * resolution];
//code for triangles
short[] triangles = new short[(resolution - 1) * (resolution - 1) * 6];
int triIndex = 0;
//looping over each vertex in the face
for (int y = 0; y < resolution; y++) {
for (int x = 0; x < resolution; x++) {
int vertexIndex = x + y * resolution;
//vector representing how close to the end of the x or y axis the loop is
Vector2 t = new Vector2(x / (resolution - 1f),y / (resolution - 1f));
//calculates the position of the vertex to place on the face
Vector3 mulA = u.mul(axisA, (2*t.x - 1));
Vector3 mulB = u.mul(axisB, (2*t.y-1));
Vector3 point = u.add3(normal, mulA, mulB);
//point = u.normalize(point);
vertices[vertexIndex] = point;
//puts the vertices into triangles
if (x != resolution - 1 && y != resolution - 1) {
triangles[triIndex + 0] = (short) vertexIndex;
triangles[triIndex + 1] = (short) (vertexIndex + resolution + 1);
triangles[triIndex + 2] = (short) (vertexIndex + resolution);
triangles[triIndex + 3] = (short) vertexIndex;
triangles[triIndex + 4] = (short) (vertexIndex + 1);
triangles[triIndex + 5] = (short) (vertexIndex + resolution + 1);
triIndex += 6;
}
}
}
float[] verticeList = u.vectorToList(vertices);
Mesh m = new Mesh(true, resolution * resolution, triangles.length, new VertexAttribute(Usage.Position,3,"a_Position"));
m.setIndices(triangles);
m.setVertices(verticeList);
return m;
}
//generates a cube Mesh with resolution vertices along each face
public Mesh generateFaces(int resolution, float scale) {
MeshBuilder meshBuilder = new MeshBuilder();
meshBuilder.begin(new VertexAttributes(new VertexAttribute (Usage.Position, 3 ,"a_Position")));
Vector3[] faceNormals = {
new Vector3(0,1*scale,0), //up
new Vector3(0,-1*scale,0), //down
new Vector3(-1*scale,0,0), //left
new Vector3(1*scale,0,0), //right
new Vector3(0,0,1*scale), //forward
new Vector3(0,0,-1*scale) //back
};
for (int i = 0; i < faceNormals.length; i++) {
meshBuilder.part("part"+ Integer.toString(i), GL20.GL_TRIANGLES);
meshBuilder.addMesh(createFace(faceNormals[i], resolution));
}
Mesh mesh = meshBuilder.end();
return mesh;
}
u is just a utilities class i created to store some math functions.
I then render it like so:
#Override
public void render () {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
shader.bind();
shader.setUniformMatrix("matViewProj", cam.combined);
//rendering mesh
mesh1.render(shader, GL20.GL_LINE_STRIP);
[...]
}
I now want to make a model out of that mesh where each of the 6 faces will have a different color.
I thus tried to do it using a ModelBuilder following the LibGDX wiki, like so:
public Model generateModel(int resolution, float scale, Color[] colors) {
Vector3[] faceNormals = {
new Vector3(0,1*scale,0), //up
new Vector3(0,-1*scale,0), //down
new Vector3(-1*scale,0,0), //left
new Vector3(1*scale,0,0), //right
new Vector3(0,0,1*scale), //forward
new Vector3(0,0,-1*scale) //back
};
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
for (int i = 0; i < faceNormals.length; i++) {
Mesh mesh = createFace(faceNormals[i], resolution);
MeshPart part = new MeshPart("part"+Integer.toString(i),mesh, 0, mesh.getNumVertices() ,GL20.GL_TRIANGLES);
modelBuilder.node().parts.add(new NodePart(part, new Material(ColorAttribute.createDiffuse(colors[i]))));
}
Model m = modelBuilder.end();
return m;
}
And then i rendered it using a ModelBatch and ModelInstance :
#Override
public void create () {
//creates an environment to handle lighting and such
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight,0.4f,0.4f,0.4f,1f));
environment.add(new DirectionalLight().set(0.8f,0.8f,0.8f,-1f,-0.8f,-0.2f));
modelBatch = new ModelBatch();
//handling the inputProcessors of the camera and stage(UI)
multiplexer = new InputMultiplexer();
stage = new Stage();
multiplexer.addProcessor(stage);
scroll = new ScrolledInputProcessor();
multiplexer.addProcessor(scroll);
//camera (3D inputProcessor)
cam = new PerspectiveCamera(67,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
cam.position.set(10f,10f,10f);
cam.lookAt(0,0,0);
cam.near = 1f;
cam.far = 300f;
cam.update();
camController = new CameraInputController(cam);
multiplexer.addProcessor(camController);
//shaders for every vertex and every pixel(fragment)
shader = new ShaderProgram(Gdx.files.internal("shader/vertexshader.glsl").readString() ,Gdx.files.internal("shader/fragmentshader.glsl").readString());
shader2 = new ShaderProgram(Gdx.files.internal("shader/vertexshader.glsl").readString() ,Gdx.files.internal("shader/fragmentshader2.glsl").readString());
//The 2D box encompassing the screen (UI)
table = new Table();
table.setFillParent(true);
stage.addActor(table);
//skins for UI
skin = new Skin(Gdx.files.internal("uiskin.json"));
//making a slider and dressing it in the skin
Drawable knobDown = skin.newDrawable("default-slider-knob", Color.GRAY);
SliderStyle sliderStyle = skin.get("default-horizontal", SliderStyle.class);
sliderStyle.knobDown = knobDown;
slider = new Slider(3.0f, 70.0f, 1.0f, false, sliderStyle);
table.right().top();
table.add(slider).row();
//creates the unit cube and unit sphere
model = generateModel(res, 1, colors);
instance = new ModelInstance(model);
font = new BitmapFont(Gdx.files.internal("uiskin.fnt"));
batch = new SpriteBatch();
Gdx.input.setInputProcessor(multiplexer);
}
#Override
public void render () {
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
shader.bind();
shader.setUniformMatrix("matViewProj", cam.combined);
modelBatch.begin(cam);
modelBatch.render(instance, environment);
modelBatch.end();
batch.begin();
font.draw(batch, "Zoom Level : " + zoomLevel, 1000f, 100f);
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
However, when i run the program, nothing is rendered, just the gray void.
Gray void of nothingness
My question is: How do I get my model to render?

RectF goes out of borders on Canvas

I'm improving a simple Android game called Arkanoid, where I'm having a small problem drawing a RectF on a Canvas.
I implemented a power-up option where, if you take this power-up, the Paddle streches from a 200x Paddle to a 500x Paddle.
private RectF r;
private Paint paint = new Paint();
private Bitmap flipperBit;
// Draw Paddle
flipperBit = BitmapFactory.decodeResource(getResources(), R.drawable.flipper);
paint.setColor(Color.WHITE);
if (powerUpTaken) {
r = new RectF(flipper.getX(), flipper.getY(), flipper.getX() + 500, flipper.getY() + 40);
} else {
r = new RectF(flipper.getX(), flipper.getY(), flipper.getX() + 200, flipper.getY() + 40);
}
canvas.drawBitmap(flipperBit, null, r, paint);
The main problem is that when I hit the powerup, the Paddle successfully streches from 200 to 500, but goes out of border as in the gif below, thinking it's still a 200x Paddle.
Please note that all of this , it's written inside the onDraw overrided-function.
I know, I need to implement a way to stretch the Paddle for x seconds, but as of now I want to make it work first.
Any suggestion would be really appreciated. :)
//set to ZERO if not needed
final cMargin = 10;
int cPaddingWidth;
final int cPaddingHeight = 40;
final RectF cRectF = new RectF();
if (powerUpTaken) cPaddingWidth = 500;
else cPaddingWidth = 200;
cRectF.left = Math.max(cMargin, flipper.getX());
cRectF.right = cRect.left + cPaddingWidth;
if (cRectF.right > (this.getWidth() - cMargin)) {
cRectF.left = (this.getWidth() - cMargin) - cPaddingWidth;
cRectF.right = cRectF.left + cPaddingWidth;
}
cRectF.top = Math.max(0, flipper.getY());
cRectF.bottom = cRect.top + cPaddingHeight;
r.set(cRectF);

Centering map or camera 2D game

I've tried so many solutions that it's possible that my code is a bit mixed up, but whatever I try, it just won't work.
Basically I made a map with Tiled, where my player can run around and bump into stuff. I want the whole map to be visible for the whole time (it's 20 by 15, 64 pixels a tile). The camera doesn't need to move around or follow the player, it has to stay still at the center of the map.
The problem is that the map only shows in the upper right corner of the screen. When I centered the camera to the map itself it messed up the collission detection, (bumping into trees while they were not visible & walking through visible trees). So what I want to do is center the map to 0,0 where my camera also is (at least I think..).
Another thing I'd like to accomplish is that the size of the map gets resized to match different mobile phones. Tried to accomplish this with the stretchviewport, but haven't been able to test this.
public class PlayScreen implements Screen {
TiledMap map;
OrthogonalTiledMapRenderer mapRenderer;
OrthographicCamera cam;
float unitScale = 1 / 64f;
OrthogonalTiledMapRenderer renderer = new OrthogonalTiledMapRenderer(map, unitScale);
Viewport viewport;
public void show() {
map = new TmxMapLoader().load("maps/map.tmx");
mapRenderer = new OrthogonalTiledMapRenderer(map);
cam = new OrthographicCamera(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
cam.setToOrtho(false);
viewport = new StretchViewport(1280, 960, cam);
bounds = new ArrayList<Rectangle>();
for(int i = 0; i < 20; i++){
for(int j = 0; j < 15; j++){
TiledMapTileLayer cur = (TiledMapTileLayer) map.getLayers().get(1);
Cell cell = new Cell();
Vector3 center = new Vector3(cur.getWidth() * cur.getTileWidth() / 2, cur.getHeight() * cur.getTileHeight() / 2, 0);
cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
cam.update();
if(cur.getCell(i,j) != null){ //null = first layer != --> if its not
cell = cur.getCell(i, j);
System.out.println(i + ", " + j + ", " + cell.getTile().getId());
bounds.add(new Rectangle(i * 64, j * 64, 64 , 64));
}
}
}
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
mapRenderer.setView(cam);
mapRenderer.render();
cam.position.set(0, 0, 0);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
batch.draw(player.getCurrentFrame(), player.getPosition().x , player.getPosition().y);
player.update();
for(int i = 0; i < bounds.size(); i++){
if(bounds.get(i).overlaps(player.getBounds())){
int x = (int)bounds.get(i).x / 64;
int y = (int)bounds.get(i).y / 64;
TiledMapTileLayer cur = (TiledMapTileLayer)map.getLayers().get(1);
Cell cell = cur.getCell(x, y);
if(cell.getTile().getProperties().containsKey("blocked")){
System.out.println("bush");
}
player.reAdjust();
}
}
batch.end();
}
public void resize(int width, int height) {
viewport.update(width, height);
}
Nevermind, I deleted: cam.position.set(0, 0, 0); and everything seems to work just fine. Guess I already made some changes what caused it to work, just didn't see it cause this was still around.

Entitymodifiers runs but show no change

I'm making a board game and I'm stuck on problem that's been killing 3-4 hours for me now. No docs anywhere so I'm just doing guesswork without luck.
Consider this:
public void highlightBlockTest(BoardCoordinate bc) {
Log.i("highlightBlock()", "entered.");
Point p = new Point(bc.getPuzzlePiece().getDestination());
Rect rect = getBoardCoordinateRectFromPoint(p);
int x = rect.getX();
int y = rect.getY();
int w = rect.getWidth();
int h = rect.getHeight();
Entity e = new Entity(0, 0);
Rectangle r;
r = new Rectangle(x, y, w, 5);
e.attachChild(r);
r = new Rectangle(x, y, 5, h);
e.attachChild(r);
r = new Rectangle(x + w - 5, y, 5, h);
e.attachChild(r);
r = new Rectangle(x, y + h - 5, w, 5);
e.attachChild(r);
SequenceEntityModifier sem = new SequenceEntityModifier(
new DelayModifier(1f),
new AlphaModifier(1f, 0.0f, 1.0f, new IEntityModifierListener() {
#Override
public void onModifierStarted(IModifier<IEntity> arg0, IEntity arg1) {
System.out.println("Alpha start!");
}
#Override
public void onModifierFinished(IModifier<IEntity> arg0, IEntity arg1) {
System.out.println("Alpha stop!");
}
})
);
e.registerEntityModifier(sem);
this.mScene.attachChild(e);
return;
}
This code is supposed to draw a "highlight" rectangle for a particular block. The rectangle draws all right, but the AlphaModifier does not applicate its values on the entity in question. The DelayModifier works just fine.
I added ModifierListener just to see if it gets called, and it does; I see "Alpha start" and "Alpha stop" in Logcat. But the highlighted rectangle is still there, clearly visible on the board.
As a last resort I added a MoveModifier as well to move the rectangle 50 pixels to the right during 5 seconds, and the rectangle was moved off screen instantaneous.
Why aren't these modifiers working as expected?
You need to set the blend function, call .setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); on the entities.

Detecting Hough circles android

I am trying to detect circles using android. I succeeded to implement the detect lines algorithm but nothing gets displayed when trying the draw hough circles algoritm.
Here is my code:
Mat thresholdImage = new Mat(getFrameHeight() + getFrameHeight() / 2, getFrameWidth(), CvType.CV_8UC1);
mYuv.put(0, 0, data);
Imgproc.cvtColor(mYuv, destination, Imgproc.COLOR_YUV420sp2RGB, 4);
Imgproc.cvtColor(destination, thresholdImage, Imgproc.COLOR_RGB2GRAY, 4);
Imgproc.GaussianBlur(thresholdImage, thresholdImage, new Size(9, 9), 2, 2 );
Mat circles = new Mat();
Imgproc.HoughCircles(thresholdImage, circles, Imgproc.CV_HOUGH_GRADIENT, 1d, (double)thresholdImage.height()/70, 200d, 100d);
Log.w("circles", circles.cols()+"");
for (int x = 0; x < circles.cols(); x++)
{
double vCircle[]=circles.get(0,x);
Point center=new Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
int radius = (int)Math.round(vCircle[2]);
// draw the circle center
Core.circle(destination, center, 3,new Scalar(0,255,0), -1, 8, 0 );
// draw the circle outline
Core.circle( destination, center, radius, new Scalar(0,0,255), 3, 8, 0 );
}
You may have got this sorted by now, but a few things. I'd check your circles mat actually has some results; sometimes vCircle seems to come back null; try one of the other versions of HoughCircles:
iCannyUpperThreshold = 100;
iMinRadius = 20;
iMaxRadius = 400;
iAccumulator = 300;
Imgproc.HoughCircles(thresholdImage, circles, Imgproc.CV_HOUGH_GRADIENT,
2.0, thresholdImage.rows() / 8, iCannyUpperThreshold, iAccumulator,
iMinRadius, iMaxRadius);
if (circles.cols() > 0)
for (int x = 0; x < circles.cols(); x++)
{
double vCircle[] = circles.get(0,x);
if (vCircle == null)
break;
Point pt = new Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
int radius = (int)Math.round(vCircle[2]);
// draw the found circle
Core.circle(destination, pt, radius, new Scalar(0,255,0), iLineThickness);
Core.circle(destination, pt, 3, new Scalar(0,0,255), iLineThickness);
}
(I swapped your code into mine, renamed some stuff and swapped it back, I think I've got it back so it works...)
B.

Categories