LibGdx RayCast box2d debug (visual on screen) - java

Can someone help me?
I want see the raycast in the game screen (for debugging..).
What is the best way to achieve that?
Please note that i use "box2d". and the way that i draw stuff to the screen is with animation..
So does it means that i need to create an "EdgeShape"? and then this is my debug line?
Please if there is any suggestions that you can give or ideas i really don't mind how to implement, all i want is a proper way to see the Raycast.
I could not found a good way to draw the Raycast, i saw someone that use batch.draw(); - but i guess that it won't work for me, because that way that my game work's is with box2ds shapes and animation? is that right?
Thanks so much!
world.rayCast(callback, enemy.getBody().getPosition(),
new Vector2(enemy.getBody().getPosition().x-500, enemy.getBody().getPosition().y));
}
RayCastCallback callback = new RayCastCallback() {
#Override
public float reportRayFixture(Fixture fixture, Vector2 point,
Vector2 normal, float fraction) {
if(fixture.getBody().getUserData() == ModelType.PLAYER) {
System.out.println("hey!");
return 0;
}
return -1;
}

I debug it now with ShapeRendrer:
shapeRenderer.setProjectionMatrix(batch.getProjectionMatrix());
shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
shapeRenderer.line(rayStart,rayEnd);
shapeRenderer.setColor(Color.RED);
shapeRenderer.end();
I just add it to the same class, where my enemy is.
And i also taking care of the points (the Vector2):
world.rayCast(rayCastCallback, p1, p2);
To be updated, as my enemy moves.

Related

libgdx how to detect collisions?

I have a Problem to detect collisions. I'm using TiledMap and created a virtual joystick, so that its possible to move in every direction not just left, right, top, bottom. The Point of View is directly 90 degrees from the top.
I don't know if that's the purpose of a TiledMap, but I thought the maps are easy to create. But now I 've got Problems with the collision detection. Since the map is not arranged like a chessboard, for example, I need to check the whole Sprite for collision. Can you please explain me to how that works?
Thank You
First of all I recommend you to checkout this question to clear up some things, and to get a basic Idea how collision detection works with TiledMaps.
Summarized: Using a TileEditor you can add different layers to your TiledMap. One of theese layers can be a object layer which can be used for collision. For how to create and access the layer please checkout the linked question.
For your example there are some central questions which needs to be cleared out first:
Which shape and size do the colliding objects have?
Can the objects move in between two tiles?
What should happen on collision?
Pokemon is a super easy example. The Player has the size of exactly one tile and can not move in between them. If there is a collision the player just can't move.
If that is what you want you can just add a check before moving any object: If the next tile isn't valid just don't move the object. For the collision check you can just adapt the example code from the first answer.
On the other end of the specturm you could have different shaped objects with differnt scales which have a dynamic velocity and should bounce of the objects on the TileMap. In that case it could be clever to use box2d for collision detection like in this answer.
So depending on your needs just try to adapt any of the answers I linked. Maybe just start with a super simple box collision try to extend your code.
use this method
void isCollition(Object x, Object y) {
Boolean collide = false;
if (x.getX() + x.getwidth() < y.getX() + y.getWidth() ||
x.getY() + x.getHeight() < y.getY() + y.getHeight() {
collide = true;
}
return collide;
}

libGDX - how to remove existing spritebatch on screen?

So I've been looking through and experimenting some stuff but can't quite get how to remove pre-existing spriteBatch on screen.
so basically
I have initiated
batcher.begin();
(blah blah blah)
AssetLoader.font.draw(batcher, "Hey guys", x, y);
something like this...
now I wish to delete/remove/undraw this thing on screen...
how do I do that without using if statement because.. if I start using If statements everything is going to get sooo messy.
Thanks so much!
Its generally accepted practice in an OpenGL application to clear the screen every time and re-draw the entire screen.
So, to "erase" something, you just stop drawing it.
boolean wantToSeeThis = true;
...
void render() {
batcher.begin();
(blah blah blah)
if (wantToSeeThis) {
AssetLoader.font.draw(batcher, "Hey guys", x, y);
}
}
void hideIt() {
wantToSeeThis = false;
}
It is a bit unclear what you are asking. By default your screen gets cleared every frame with this line in the Render method.
gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
Then obviously we need statements of when we want to draw things. If you code your whole program in a single class this obviously gets messy quick. But Java is OOP which means you can add a classes with there own Draw/Render method and there own statements as to when they should be drawn. I suggest you start learning the basics of OOP.

Libgdx rotate ModelInstance

I am developing my first libgdx 3D game. Until now i can move arround in a maze-like (hardcoded) world, collision detection works. Also i have some enemies with working A* Pathfinding.
I also loded my first (pretty ugly) Blender model, using FBX-Conv to get a .g3db file. For some reason the model lise on the floor instead of standing. Maybe i had some wrong settings when i exported it as .fbx.
For that i tryed to rotate() him arround the z-Axis by 90 degrees by calling:
modelInstance.transform.rotate(Vector3.Z, 90) in the show() method of my Screen, after loading the Model and instantiating my ModelInstance (at a given position). For some reason it did not rotate. Then i put the rotate method in the render(delta), thinking, that it would now rotate 90 degrees every render loop. But instead it was standing still, like it should.
Okay, but now i want the modelInstance to rotate to where it actually looks, meaning it should rotate, depending on my enemies Vector3 direction.
I am allready setting his position with modelInstance.transform.setTotranslation(enemie.getPosition()) which works perfect. So i thought i can also use modelInstance.transform.setToRotation(Vector3 v1, Vector3 vs), with v1 = enemie.getPosition() and v2 = enemie.getPosition().add(enemie.getDirection). Note, that the position Vector is not used directly, as it would change its values inside the add() method.
Doing this, i don't see the object anymore, meaning also its position is wrong.
Why is this happening?
And how can i rotate my modelInstance by using the direction vector?
Thanks a lot.
I solved this with #Xoppas help. The problem was:
i used setToTranslation to move my Model to a given position, but this als resets the rotation
I missunderstood the setToRotation(Vector3, Vector3) method.
So the solution was to to the setToTranslation first, and then use setToRotation(Vector3 direction, Vector3 face), where direction is the direction, in which my Model is looking and face is the face, which should look in this direction, in my case the Vector3.X.
Hope it helps someone else.
Worse case scenario, you could modify the transformation matrix using:
ModelInstance.transform.rotate()

can anyone explain the math behind the red ship in this simple game? [homing missile esque]

the game is a little flash component found here:
http://www.rydeman.com/erik/skepp2.html
i found that link here:
http://board.flashkit.com/board/archive/index.php/t-175556.html
I have been using/converting the examples they give in the second link but cant get my "missile" to behave correctly. I am using java and andEngine combo. Here is what I have right now:
public boolean onSceneTouchEvent(Scene pScene,TouchEvent pSceneTouchEvent) {
int Missile_speed=20;
int dx=(int) (pSceneTouchEvent.getX()-(face.getWidth()/2));
int dy=(int) (pSceneTouchEvent.getY()-(face.getHeight()/2));
double distance=Math.sqrt((dx*dx)+(dy*dy));
//dx/=distance; /** not really sure what " /= " is on this line and the next **/
//dy/=distance;
if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN)
{
//to do
}
if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_MOVE)
{
face.registerEntityModifier(new MoveModifier(1, face.getX(), (int)(dx/distance)*Missile_speed, face.getY(),(int)(dy/distance)*Missile_speed, EaseQuadOut.getInstance()));
}
if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_UP)
{
//to do
}
return true;
}
this code just makes the object travel to the upper right hand corner of the screen and it doesnt move after that. so i am missing something
my end goal is to have an object that will chase the users touch coordinates. I know how to have the object follow such coordinates but I dont want it to follow the exact path, but rather the shortest path to the most updated coordinates. so more like an intercept course
thank you
dx and dy start with the distances in x and y to your target position (I guess you figured out that much, but bear with me)
When you divide dx or dy by the distance, you now have those values constrained between 0 and 1, and these values tell you where it is relation to that axis, without regard to distance (example: if the target is exactly to the right, no matter how far or close, dx/dist is 1 and dy/dist is 0).
Now when you multiply Missile_speed by those axis, the missile will chase that direction in it's maximum speed.
Those values between 0 and 1 are the cosine of the angle between the target position and the missile, btw (it's important that you visualize this so you can think through similar problems in these terms on your own in the future).
I'm not sure this is what you wanted - it seems you wanted the trigonometry of the situation explained and not working code, so that's what I tried to do (not sure if I succeeded). Really understand this, and you should have no problem with similar problems in the future (and these situations are really ubiquitous in game development, btw)

Making my canvas scroll-able without a major overhaul

I'm in the process of developing a 2-D game for android which primarily i'm using as an experience to learn the in's and out's of programming for android apps, so naturally i run into a lot of puzzles to work through. Currently, my main activity instantiates a custom class which extends SurfaceView and implements SurfaceHolder.Callback. This view instantiates a thread which handles most of the logic and all the graphics processing (this includes instantiating a canvas and drawing to it., etc.
Well, being that I am a beginner I wasn't thinking when I started that designing the canvas to be much larger than the screen and to allow users to scroll around to see all parts of the canvas... but alas, that's what I need to happen.
If there is an easy way to do this, please let me know.
My best guess is putting the actual creation of the canvas in a separate class which extends ScrollView and somehow just calling all the Draw()'s to that canvas from my thread. is this possible? my click events are actually captured from the main activity (just fyi).
The best option would be to use a Camera to translate the canvas. Do something like this:
// Creates a new camera object
Camera mCam = new Camera();
float startX;
float startY;
#Override
public void onTouch(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
startX = event.getX();
startY = event.getY();
}
else if(event.getAction() == MotionEvent.ACTION_MOVE)
{
float x = event.getX();
float y = event.getY();
// Lets you translate the camera by the difference
mCam.translate(x -startX, startY - y, 0.f);
startX = event.getX();
startY = event.getY();
}
}
#Override
public void onDraw(Canvas canvas)
{
// Draw here the objects you want static in the background
canvas.drawBitmap(mBackground, 0, 0, null);
canvas.save();
mCam.applyToCanvas();
// Draw here the objects you want to move
canvas.drawBitmap(mBall, 0, 0, null);
canvas.restore();
// Draw here the objects you want static on the forebround
canvas.drawBitmap(mScore, 0, 0, null);
}
Notice that you are drawing mBall at 0,0 but due to the camera translation it will move by the amount specified. I hope this helps. Have fun :)
I slept on the problem and came up with (if i don't say so myself) A brilliant, relatively simple and elegant solution. Sorry to toot my own horn but I was literally ecstatic that i was able to come up with this.
If anyone is thinking of using this method there are a couple of conditions that made this a good choice. First, all of my objects are drawables with predefined locations using the setBounds(int,int,int,int) method, all objects also store their own coordinates for the location to draw on the canvas and all objects are called in hashmaps which allows me to call and process all the objects in existence.
Now I was thinking about what kabuko said and how it's such a waste to draw a huge canvas and how id run into click event problems, that's when I came up with this.
when a screen touch event occurs near the edge of the screen, a custom method Scroll() is called which loops through every object and adjusts the stored coordinates of the object location depending on which direction the user is trying to scroll. after it increments the objects location, it (in parallel) increments a pair of variables for x and y offset. This offset is then factored into the coordinates of the touch events so that objects can still be selected by touch regardless of the position the screen is scrolled to.
then for performance's sake a simple if statement makes it so that draw is only called on an object if that objects coordinates fall in the range of the screen.
Sorry to gloat but I really surprised and impressed myself with this, haha. I've really only been coding about a month and I almost have a fully functional 2D strategy game!
Java for dummies paid off, lol.
You could give your approach a try, even though it's not really a strategy I'd ever use myself. I suspect you're going to run into some issues with that approach anyway though. If your game already uses touch for input, you're going to have conflicts. Also, if performance is at all a concern (especially if you have any animation), you don't want go with this approach.
If you're going as far as dealing with threading, performance probably matters. Drawing is expensive, and if you make a huge canvas, you'll have to be rendering the whole thing and it will cost you. You should only draw what's on the screen (more or less). Sorry, but you'll probably need a "major overhaul"...
That said, it's really not that bad to deal with scrolling. You probably have coordinates for everything you're drawing. All you need to do is keep track of your "current coordinates" and then translate your drawing x and y by your current x and y. Dealing with the performance stuff, there's a lot you can do, but that's starting to get a bit off-topic. Take a look at these videos if you want to know more:
http://www.youtube.com/watch?v=U4Bk5rmIpic
http://www.youtube.com/watch?v=7-62tRHLcHk
The simple trick with side-scrolling games is to divide your world into tiles, where each tile has a specified amount of area.
Displaying a Tile Based Map
Scrolling a Tile Based Map

Categories