I am developing an android game on Eclipse in which a sprite is jumping on several platforms to get to the top but I am having difficulties. Here is my case: I have the character sprite (I'll name this as Sprite1 in this case) that moves and I am creating another 3 sprites(the platforms) at random positions when my app starts. The platforms are successfully created when the app starts. But the collision between them and Sprite1 is not detected. I tried many solutions and I am stuck for a couple of days now. Any help or suggestion will be appreciated.
I tried making rects when the platforms are created then using the rects to detecting collisions but they still don't collide. I use Java language. :)
I use this to create the sprites and detect collisions:
Creating platform sprites (this is how i randomly spawn platforms, if there are mistakes here, i'm sure i just copied wrong because the creating or platform sprites works correctly.):
public void addRandomPlatform(){
Random rand = new Random();
randPlat = CCSprite.sprite("platform2.png");
randPlat.setPosition(actualX, actualY);
actualY -= (int)(randPlat.getContentSize().height*4);
addChild(randPlat,2);
}
Then I just call this method when my app starts.
Detecting Collision:
playerRect = CGRect.make(player.getPosition().x - (player.getContentSize().width / 4.0f),//- (player.getContentSize().width / 2.0f),
player.getPosition().y - (player.getContentSize().height / 2.0f),
player.getContentSize().width/3.0f,
player.getContentSize().height/8.0f);
if(CGRect.intersects(playerRect, randPlat))
{
*my codes for stopping the jump*
}
I hope this is clear. Thanks in advance!
It looks like the randRect is a CCSprite, and not a CGRect. You should create a CGRect(of the random platform) the same way you created the playerRect.
Also, why do you divide the player's width/height by respectively 3 and 8? I don't think that's what you want, and it causes the playerRect to be only a thirth of the width, and 1/8 of the height of the actual sprite.
#Override
public boolean ccTouchesEnded(MotionEvent event) {
CGPoint point = ranSprite.getPosition();// THE POSITION MUST BE YOUR RANDOM SPRITES POSITIONS
List<CCNode> childsList = this.getChildren();
for(CCNode childSprite : childsList){
if(childSprite.getTag() == Constants.PLAYER_TAG && childSprite.getBoundingBox().contains(point.x, point.y)){
// Do what ever you want
}
}
Related
I have a TriangleMesh in javafx and a 2D point in screen space and i want to check whether any triangles in the mesh intersect with that point(basically same as clicking a point in the mesh except that i already have a predefined screen coordinate)
Note that i don't care where the intersection happened etc but only the fact whether it intersected or not.
I did try googling this and found some useful answers, especially one by José Pereda here: https://stackoverflow.com/a/27612786/14999427
However the links are down
Edit: i did find a working link to it, however it just hardcodes the origin/target and im not sure how to compute these from the 2d screen point
Another idea i had was to copy the implementation from openjfx but after some research i figured that i'd have to copy a lot of internals and even then i wasn't sure if i would get it working so i scrapped that idea.
Goal: i want to use my mouse to create a rectangle at an arbitrary position in the mesh and then find all triangles that are inside that rectangle (i believe it's usually called rectangle selection in 3d modeling software)
Update: converting each triangle to 2d screen coordinates using Node#localToScreen and then doing a 2D point inside triangle test works perfectly however it also selects faces that are culled.
Update 2: after also doing the culling myself it works quite well (it's not perfect but it's mostly accurate)
Current code:
Point2D v1Screen = view.localToScreen(mesh.getPoints().get(0), mesh.getPoints()
.get(1), mesh.getPoints().get(2));
Point2D v2Screen = view.localToScreen(mesh.getPoints().get(3), mesh.getPoints()
.get(4), mesh.getPoints().get(5));
Point2D v3Screen = view.localToScreen(mesh.getPoints().get(6), mesh.getPoints()
.get(7), mesh.getPoints().get(8));
Point2D point = new Point2D(mouseX, mouseY);
boolean inTriangle = pointInTriangle(point, v1Screen, v2Screen, v3Screen);
// Back-face culling
double dxAB = v1Screen.getX() - v2Screen.getX();
double dyAB = v1Screen.getY() - v2Screen.getY();
double dxCB = v3Screen.getX() - v2Screen.getX();
double dyCB = v3Screen.getY() - v2Screen.getY();
boolean culled = ((dxAB * dyCB) - (dyAB * dxCB)) <= 0;
if (inTriangle && !culled) {
view.setMaterial(new PhongMaterial(Color.BLUE));
System.out.println("Intersected");
}
I think the answer to this question may help you. How to correctly obtain screen coordinates of 3D shape after rotation If you can compute the screen coordinates of a 3D shape (triangle) the hit test should then be simple.
I'm making a 2D platformer game. I have created a texture for the platform, that is meant to be repeated over and over to fill the entire platform, without going over. My first attempt was to draw all the pixels from the bitmap manually, but this caused the background to flicker through while moving the platform (the movement and drawing threads are seperate, so the movement can run at a specific speed, while the FPS doesn't need to suffer). I found this technique worked better:
// Init
bitmap = new BitmapDrawable(res, Texture.PLATFORM.getBitmap());
bitmap.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
// Drawing loop
int x = getX() + (isStill() ? 0 : (int)MainActivity.offsetX);
int y = getY() + (isStill() ? 0 : (int)MainActivity.offsetY);
bitmap.setBounds(x, y, x + getWidth(), y + getHeight());
bitmap.draw(canvas);
However, the bitmap appears to be staying static while the platform is acting as a "view hole" to see through to the bitmap. The only work around I can think of is to somehow "offset" the static bitmap:
bitmap.offset(x, y);
Obviously, that isn't a function. I couldn't find one that would do what I want when looking through the docs.
To summon things up, the BitmapDrawable is causing the background to not move with the platform, making it look super weird.
Thanks in advance!
Try these tips in your code:(I assumed the game moves forward in the horizontal direction)
The GUY should only move up and down(with the appropriate touch input) and not forward and backward as you want the focus(or camera alternatively) solely on the GUY.I noticed that the WALL was moving up in your video when the GUY moved from initial higher position of the wall to little bit lower position later, rectify this because the GUY should move down(try to implement Gravity effect).
The WALL should only move forward(mostly) and backward(less often I guess).The WALL shouldn't move up and down normally. Do not apply Gravity effect to it. You can create at least 2 BitmapDrawable instance of WALL for a screen. They are going to be reused sequencially(for eg: If the 1st one goes totally outside of the screen, reshow it in the desired position using setBounds() method) and continue same for others the whole game.
The currently BLUE BACKGROUND, if it is a part of a larger map, then it needs to be appropriately offsetted.
One of the obstacles that I can think of at the time of writing this is to move the WALL down until it goes out of the screen which results in the death of the GUY.
At those places, where I have used the word move, you need to use the setBounds(a, b, c, d) method to make necessary position based changes as I didn't find other way to update the position of a BitmapDrawable instance. I think, you need to use game framework like libGdx to get method of luxury like setOffset(x, y) or of similar sort.
Sorry that I could only present you the ideas without specific code as I do not have past experience working in a project like this. Hope, it helps you in anyway possible.
I'm making a platformer game. The jumping and movement are working, and now I want to program the collisions. I have a sort of idea as to how this will work:
I wasn't sure whether this question should be here or in the game dev site.
I have two Vector2's - velo and momentum (velo is the velocity). Both are (0, 0). The momentum is what's added to the velocity each frame.
Each frame, I first get the input. Momentum is increased and/or increased based on the keys pressed (e.g: if (Gdx.input.isKeyPressed(Keys.A)) { momentum.x -= speed; })
I then multiply the momentum by 0.15. This is so that it slows down.
After this, I multiply the velocity by 0.8.
Then, I add the momentum to the velocity, to increase the velocity, as
this is what actually moves the player.
I then add the velocity to the position of the player.
To apply the gravity, I add a gravity vector (0, -10) to the position of the player.
So I need to find a way to move the player, but not allowing it to overlap any part of the world. The world is made up of lots of Rectangle instances. The player's body is also an instance of Rectangle. Would it be easier to rewrite the collisions using Box2D? What I've tried is checking if the player overlaps any rectangles when it's moved, and if it will, not moving it. But this doesn't seem to take everything into account - sometimes it works, but other times, it stops before touching the world.
TL;DR: I want to make collisions of my player with a world which is stored as a grid of rectangles. How would I do this, as my player is also a Rectangle. Would it be easier to use Box2D?
This answer gives a good overview about the details of collision detection:
https://gamedev.stackexchange.com/a/26506
However, that might be a bit overwhelming if you just want to get a simple game going. Does your game loop happen in fixed interval or is it dependent on the framerate? Maybe you could solve a part of your issue by simply dividing the collision detection into more steps. Instead of moving the full way during one update, you could make 10 little updates that each move you only a 10th of the distance. Then you do a collision check after each step, so it's less likely that you stop too early or move through thin objects.
That would of course be more taxing on the performance, but it's a naive and easy to implement approach to a solution.
EDIT:
Just wrap the position update in a for loop. I don't know how your code for collision checking and updating, but the general structure would be something like
for (int i = 0; i < 10; i++) {
newPosX += deltaX * 0.1; // 1/10th of the usual update
newPosY += deltaY * 0.1; // 1/10th of the usual update
if (checkCollision(newPosX, newPosY))
{
posX = newPosX;
posY = newPosY;
}
else
{
break; // We hit something, no more mini-updates necessary.
}
}
My circumstance
I am making a 3D LibGDX game. I am using a custom camera controller, based off of the one over here. It takes out the use of delta Y, when determining where to move the player, so that they can stay on the same level whether they are looking up or down.
My problem
My problem is that whenever the player looks too far up, or down, the camera kinda starts spazing out. I believe that it is trying to look either strait up, or down. My problem is that I don't want that. In previous projects I have tried to set a limit like so:
if(camera.direction.y + deltaY >= 0.9){
return;
}
(Code might not be exactly correct), but when that happens, the player usually cannot see enough.
My code
There is a link to my code here.
I got my code fixed with the help of one of the fine fellows over at Github. Here is my new FirstPersonCameraController#touchDragged:
float deltaX = -Gdx.input.getDeltaX() * degreesPerPixel;
float deltaY = -Gdx.input.getDeltaY() * degreesPerPixel;
camera.direction.rotate(camera.up, deltaX);
Vector3 oldPitchAxis = tmp.set(camera.direction).crs(camera.up).nor();
Vector3 newDirection = tmp2.set(camera.direction).rotate(tmp, deltaY);
Vector3 newPitchAxis = tmp3.set(tmp2).crs(camera.up);
if (!newPitchAxis.hasOppositeDirection(oldPitchAxis))
camera.direction.set(newDirection);
(I removed a couple of parts that are specific to my game)
I got some difficulties because i dont know how to code efficient.
I'm creating a vertical scrolling shooter & i wanna spawn a large number of enemies.
At certain y-coordinates of the map & give them a certain x coordinate.
If been doing testing this with a couple of enemies and in my Enemy-class the code i'm using now looks like this:
if (Background.bgY == -3972 && active == 0) {
active = 1;
type = 1;
centerX = enemyXstart4;
KnightmareGame.activated = 1;
KnightmareGame.activatedatY = Background.bgY;
}
Which basically looks for if the scrolled background is at coordinate Y, activate an enemy(bomb) of type 1 and give it starting coordinate centerX, activatedatY.
This means that for every single enemy im writing this block of code...
Then in my KnightmareGame Class (which holds the routine where the enemies get drawn on screen) i'm drawing every enemy manually, which looks osmething like this:
g.drawImage(currentBomb, bo1.getCenterX(), bo1.getCenterY(), this);
g.drawImage(currentBomb, bo2.getCenterX(), bo2.getCenterY(), this);
g.drawImage(currentBomb, bo3.getCenterX(), bo3.getCenterY(), this);
And in my collision detection method Im also checking every enemy 1 by 1:
if (projectileRect.intersects(KnightmareGame.bo1.bombRectangle)) {
visible = false;
if (KnightmareGame.bo1.health > 0) {
KnightmareGame.bo1.health -= 1;
}
if (KnightmareGame.bo1.health == 0) {
Enemy.animateFire= true;
etc., etc.
The problem is that the total amount of enemiess i exceeds 50, so if i would continue coding them 1 by 1 the code would get real messy.
What i was thinking of was that I might make an array list of all the y coordinates where i wanna spawn enemies with their subsequent x coordinate.
For example at -3900 i wanna spawn an enemy at x coordinate 200. At -3800 at x coordinate 300, etc. So an array list where every position holds 2 variables (x,y)
I just dont know (first of all) how to code for this array list.
And second. I have got no clue of how to automate my draw method like
g.drawImage(currentBomb, bo1.getCenterX(), bo1.getCenterY(), this);
I'm thinking of a loop, but dont know how the code...
Collision detection: here i also collision detect in ONE block of code for every enemy instead of compare every enemy in a single seperate block of code with my projectile.
Does any1 know how to do this? Or maybe if I should do it differently then what i'm thinking of right now?
Help will be very much appreciated!
Handling multiple enemies
Create an ArrayList<Enemy> enemies;
Then use
for (Enemy bo : enemies) {
// logic for each enemy.
}
Don't forget to remove old enemies after destroying or going out of screen.
Don't keep creating new objects every time. Use a object pool for efficiency.
Improving collision efficiency
For large number of entities to be checked for collision, generally a broadphase algorithm is used.
See if it is required in your case.
You might also try some spatial optimizations like quad-trees.
These might just be wiki links, but I suppose you can search further if you know what to search for.
Hope this helps.
Good luck.