Pattern creation of collectibles - LibGdx - libgdx

I am working on a LibGdx running game.I have collectibles/coins in the game.
I have created a coin array,and spawned it throughout the game.
To improve the play,I want to make patterns of coins.Like 2 coins or 3 coins together , coins in vertical or diagonal arrangements etc.
I tried to implement this,but found it a difficult task as a fresher.
Please suggest me some code to implement patterns like triangle with an array of objects.
Like this:triangle with 3 coins in equal distance:
My coin array and method are included here:
I am adding new coins on the basis of last coin passes a particular distance on the screen.
Array<Coin> coins = new Array<Coin>();
private void createCoin() {
coinObj = objectFactory.createCoin(CoinEnum.random());
coinObj.isCollided = false;
coins.add(coinObj);
}
private void spawnCoin() {
if (coins.size == 0) {
createCoin();
} else {
Coin c = coins.peek();
if (c.getY() > (Constants.WORLD_HEIGHT / 8))
createCoin();
}
// remove out of screen coins
if (coins.size > 0) {
Coin cc = coins.first();
if (cc.getY() > Constants.WORLD_HEIGHT) {
coins.removeValue(cc, true);
}
}
}
Also hope someone can tell me the mistakes in my approach if any!
Thanks in advance!

First of all, try to model the CoinPattern:
- What is a CoinPattern?
It is just a pattern, describing an arrangement of multiple coins.
- What do I need to describe it?
As it is just a pattern, you don't need no Coins yet.
In my opinion, a list of Points (or Vector2) should be enough.
Each of these Points could describe the relative Position of the Object (in your case Coin) inside the Pattern.
Now you could create constants for your Patterns. The triangle could look something like this:
public static final PATTERN_TRIANGLE = new Vector2[] {
new Vector2(0,0),
new Vector2(1,0),
new Vector2(0,1),
};
Then you could create a method spawnPattern(Vector2[] pattern, int x, int y). This method should then create a Coin for every Vector2 in the pattern.
The position of each Coin could be calculated like this:
int posX = x + pattern[i].x;
int posY = y + pattern[i].y;
Note, that using this methode, the positions of the Coins are relative to the lower, left corner of the Pattern position.

Related

Linking buttons to imported information from csv file

I would like to ask some help turning this representation into something more interactive. Im working with Processsing latest version. The main idea is I have a table in excel, I imported it into processsing. So far so good. Displayed the values as bubbles. My problem is that would like to create buttons to See further details from each bubble. So, click a button A, the corresponding bubbleA would light up and display its specific value, according to the imported table. I dont know how to connect the button to each bubble, neither how to turn the bubble to its original state once the button is pressed again.
I`m not from the programming field, I just manage to get this far with info that I have found online, so the code must be pretty messed up. I was trying to use the libraries from Processing but I cant really understand how the controlP5 works.. I asssume the structure is way more advanced than what I can handle now.
So, if anyone can help me, I would appreciate it very much.
Table B_A_table;
//Bubble[] bubbles = new Bubble[29];
ArrayList<Bubble> bubbles = new ArrayList<Bubble>();
float scale = 3;
int c_verdeClaro = color(182,189,149);
import controlP5.*;
ControlP5 cp5;
PFont font;
PFont font1;
void setup() {
size(1000, 1000);
colorMode(HSB,255);
loadData();
font = createFont("Verdana", 18);
font1 = createFont("Verdana Bold", 18);
//font = loadFont("Arial-Black-48.vlw");
//BEGIN TEST
cp5 = new ControlP5(this);
noStroke();
smooth();
//TEST
cp5 = new ControlP5(this);
ButtonBar b = cp5.addButtonBar("bar")
.setPosition(500, 0)
.setSize(400, 20)
.addItems(split("Man Woman 20s 30s 40s 50s µµ½É±Ç"," "))
;
println(b.getItem("Man"));
b.changeItem("a","text","first");
b.changeItem("b","text","second");
b.changeItem("c","text","third");
b.onMove(new CallbackListener(){
public void controlEvent(CallbackEvent ev) {
ButtonBar bar = (ButtonBar)ev.getController();
println("hello ",bar.hover());
}
});
//WND TEST
}
void draw() {
// Display all bubbles
background(0);
Graph_Bike_Aware_Experience_Sim();
//Graph_Bike_Uso_Satisf();
pushMatrix();
translate(400,500);
for (Bubble bubble : bubbles){
bubble.display();
}
popMatrix();
}
void loadData() {
// "header" indicates the file has header row. The size of the array
// is then determined by the number of rows in the table.
B_A_table = loadTable("BikeAwareExpr_Nao.csv", "header");
for (int i = 0; i<B_A_table.getRowCount(); i++) {
// Iterate over all the rows in a table.
TableRow row = B_A_table.getRow(i);
// Access the fields via their column name (or index).
float x = row.getFloat("awareness_x")*scale;
float y = row.getFloat("experi")*scale;
float d = row.getFloat("awareness_x")*0.2;
String n = row.getString("Awareness_Bike");
Float id = row.getFloat("ID");
// Make a Bubble object out of the data from each row.
bubbles.add(new Bubble(x, y, d, n,id));
//bubbles[i] = new Bubble(x, y, d, n);
}
}
// This simple Bubble class draws a circle to the window
// and displays a text label when the mouse hovers.
class Bubble {
float x, y;
float diameter;
String name;
Float id;
// Create the Bubble
Bubble(float tempX, float tempY, float tempD, String s, Float id) {
x = tempX;
y = tempY;
diameter = tempD;
name = s;
}
// Display the Bubble
void display() {
stroke(220);
strokeWeight(1);
noFill();
ellipse(x, y, diameter, diameter);
fill(200);
textFont(font,15);
textAlign(CENTER);
text(name, x,y);
}
}
void Graph_Bike_Aware_Experience_Sim(){
pushMatrix();
int tam_table = B_A_table.getRowCount();
translate(400,500);
stroke(150);
strokeWeight(1);
line( - 100 *scale, 0*scale, + 100*scale, 0*scale);
line(0*scale, - 100*scale, 0*scale, + 100*scale);
//fill(c_verdeClaro);
noStroke();
fill(255);
textFont(font,13);
text("Experience", 40 , -97*scale);
text("Awareness", -89*scale, -10);
fill(50);
//textFont(Arial-Black-48, 32);
text("0", 10,15);
pushMatrix();
fill(0);
textFont(font1,30 );
text("IDEAL", 80*scale , -120*scale);
fill(70);
textFont(font1,25 );
text("Bicycle", 0 , -110*scale);
popMatrix();
popMatrix();
}
/*void Graph_Bike_Uso_Satisf(){
pushMatrix();
int tam_table = B_A_table.getRowCount();
translate(900,400);
stroke(150);
strokeWeight(1);
line( - 100 *scale, 0*scale, + 100*scale, 0*scale);
line(0*scale, - 100*scale, 0*scale, + 100*scale);
//fill(c_verdeClaro);
noStroke();
c_verdeClaro_grad();
c_verdeEscuro_grad();
c_Vermelho_grad();
fill(255);
text("Experience", 40 , -97*scale);
text("Awareness", -89*scale, -10);
fill(0);
//textFont(Arial-Black-48, 32);
text("word", 10, 50);
text("IDEAL", 97*scale , -97*scale);
popMatrix();
}
*/
To handle this without Object Oriented Programing, or 'OOP' is a waste of time and code.
But relax OOP also referred to as "Objects" or " Classes". It is not that hard to get. In fact it is simple to learn, I mean, the basic stuff. And it makes things very easy.
In your case, you need to build an object to represent your data. Then you create several of them, populate with data, and all will be hold together. Kind of knowing it own business.
The usual example is
Class car
has those properties
color
plate
Then you can say:
Make a Blue, 3231 car!
Make a Red, 3001 car!
and so on...
When you need it you can ask, Blue car what's your plate, and it will know.
They can also have kind of "behaviours" known as functions or methods. Those do things, so you could say: "Red, turn right", or "Bubble, show me your data!" and they will OBEY you. :)
There is no point in trying to teach this hear though. There are TONs of great tutorials around. Use Duck Duck Go :) or google if you like.
This one here are from Processing's tutorials section itself. Great ones to begin with. :)

LibGdx Bow and arrow game physics

I'm working on a new game written with LibGdx Engine and Java.
I've got a problem with some of the physics in this game.
I want to shoot the arrow in a ballistic trajectory (angry bird style)
and can't find the equation to do so .
I am using these velocity equations:
float velx = (float) (Math.cos(rotation) * spd);
float vely = (float) (Math.sin(rotation) * spd);
I add this to the current position and the arrow shoots in one direction - straight.
I thought maybe changing the rotation would help me achieve what I want (a ballistic path).
It does help, but I want to have the trajectory as well.
I saw this
ProjectileEquation class that someone already posted but didn't know how to work with it:
public class ProjectileEquation
{
public float gravity;
public Vector2 startVelocity = new Vector2();
public Vector2 startPoint = new Vector2();
public Vector2 gravityVec = new Vector2(0,-10f);
public float getX(float n) {
return startVelocity.x * (n ) + startPoint.x;
}
public float getY(float n) {
float t = n;
return 0.5f * gravity * t * t + startVelocity.y * t + startPoint.y;
}
}
I'm looking for some help to help me use this class for ballistic trajectories.
This is how I tried using it:
for(int i =0;i<30;i++)
{
Texture f = ResData.Square_1;
ProjectileEquation e= new ProjectileEquation();
e.gravity = 1;
e.startPoint = new Vector2(bow.getX(),bow.getY());//new Vector2(-bow.getX(),-bow.getY()); //My bow is opposite so it suppose to work fine
e.startVelocity = getVelocityOf(bow.getRotation());
Vector3 touchpos = new Vector3();
s.draw(f,e.getX(i) ,e.getX(i),5,5);
}
The ProjectileEquation class you post looks like it'll calculate the X and Y position given a time delta, so the float you pass in should be the time delta since you started the arrow moving (in seconds).
That code will not give you the angle of the arrow though. To find that, I would suggest you keep hold of the previous X and Y, then you can use Math.atan2() to calculate the angle based on the previous XY and the current XY. Google atan2 for a load of info on how to use it.
The very best way to do this however would be to use Box2d and model the scene correctly. Then you wouldn't have to get involved in the maths at all. I read somewhere that that's what Angry Birds uses, and is an excellent choice for modelling these sorts of physics games.
I hope your game goes well.

How to create sprite from RenderTexture cocos2d-x v3.2?

I'm trying to make a game that will take what users draw on their screens and create a sprite with a physics body. I looked around and I saw a tutorial that demonstrated this. Unfortunately the tutorial was made in Cocos2d-x v2.
http://build-failed.blogspot.com/2012/08/freehand-drawing-with-cocos2d-x-and.html
That is the tutorial that I am referring to.
http://www.cocos2d-x.org/wiki/Render_To_Texture
I tried to use that cocos2d-x tutorial to help me, but it has been labeled outdated (I tried it anyway and it didn't work). Is it still possible to allow the user to draw through this method? Or do I need to find another method to allow the user to draw the sprites? Any suggestions would be helpful. Thanks.
void GameScene::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event)
{
Point start = touch->getLocation();
start = Director::getInstance()->convertToGL(start);
Point end = touch->getPreviousLocation();
end = Director::getInstance()->convertToGL(end);
target->begin();
float distance = start.getDistance(end);
for (int i = 0; i < distance; i++)
{
float difx = end.x - start.x;
float dify = end.y - start.y;
float delta = (float) i / distance;
brush->setPosition(Point(start.x + (difx * delta), start.y + (dify * delta)));
brush->visit();
}
target->end();
}
void GameScene::onTouchEnded(cocos2d::Touch *touch, cocos2d::Event *event)
{
myObjectSprite = Sprite::createWithTexture(target->getSprite()->getTexture());
myObjectSprite->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2));
this->addChild(myObjectSprite);
}
This is what I gathered from those links. I can draw but there are a few problems.
The first attempt to draw always reflects horizontally over the center of the screen.
After a few drawings the fps begins to drop, and the app begins to take up a lot of memory and CPU usage.
The for loop in the onTouchMoved method is used because the onTouchEnded method isn't called fast enough, so there is often a large gap between each point that the onTouchMethod obtains. The loop is used to draw the brush sprites in a line between each point to prevent the gaps. However, for some reason it is not drawing in between the gaps.
Additionally, in the first link the person uses b2PolygonShape and b2FixtureDef from box2d. What are the new names of the classes in cocos2d-x v3?

LibGDX - given an arraylist of moving circles, how can i check for collision between them?

So I have 3 classes, MyGdxGame, Ball and DetectCollision. MyGdxGame initialises 4 instances of Ball (different colours and speed/direction, all bounce off the sides of the screen) and stores them as an arraylist.
This arraylist is passed through the constructor of DetectCollision:
public class DetectCollisions {
ArrayList<Ball> ball;
public DetectCollisions(ArrayList<Ball> ball) {
this.ball = ball;
start();
}
public void start() {
for(int i=0; i<ball.size();i++) {
...
}
}
Can anyone give me a hint as to where I should go with this? I just want to detect every time a ball collides with another (and eventually I'll have it print the number of collisions).
Any help highly appreciated :)
If you are going to add a lot of objects to the arraylist, use a 2D physics engine to do all the work for you. If you want to continue implementing your own functions, the very basic method to do is to implement a nested loop over the list to check every possible pair in the arraylist. The complexity is O(n^2)
for(int i=0; i<ball.size();i++) {
for(int j=i+1; j<ball.size();j++) {
check(ball.get(i), ball.get(j));
}
}
The method named check checks if given two circles collide or not. Checking two circles' collision is very easy. If the distance between the central points of the circles is smaller than the sum of the radiuses of the circles, then they collide. Check this page for further info about this.
This is very easy to accomplish if you let each Ball have bounds of type Circle.
You can make a circle as follows: Circle ballBounds = new Circle(float x, float y, float radius) This circle can act as the bounds of each ball ultimately allowing you to check if they collide using the Intersector class.
Having each Ball's boundary we can easily loop through the ArrayList<Ball> and check how many collide. For example:
ArrayList<Ball> ball = new ArrayList<Ball>(); // You need to add Balls to this ArrayList
Intersector intersector = new Intersector();
int counter = 0;
for(int i = 0; i < ball.size()-2; i++){
if(intersecor.overlaps(ball.get(i), ball.get(i+1)){
counter++;
}
i++;
}

AS3: Viewports without an end

I'm making a space navigation game. So it starts with the user on the spaceship and then when he press the up key the ship goes forward, the 'map' is always different, I have 5 variations of stars and 2 variations of planets, so they basically 'spawn' randomly while the user navigates. I can make the key detection, the movie clips generator code, but I don't know how do I make the navigation code, I mean how do I make the viewport move when the user press the key, ... I've saw a code that I didn't understand too well that the guy basically created a giant movie clip that moves according to the key that was pressed. That won't work in my case because I want it to generate everything randomly and when the user press the down arrow, I want it to go back, with the same 'map' that he was before. Please help me out guys I'm totally confused with all this viewport thing. And also, I want the game to run fast, I'm kind of new to the Action Script, and I don't know if it gets heavy if you are rendering objects that are not being displayed, if so will a simple 'obj.visible = false' works? Thanks in advance.
What I do here is:
Create a Map class with a property camera which is another custom class MapCamera.
The MapCamera has five properties:
_x
_y
map - a reference to the instance of Map owning this MapCamera
offsetX
offsetY
The offset values represent the x and y spacing from the left and top edges of the screen, which should be set to half of the stage width and height so that the camera will centre on the stage correctly.
The _x and _y properties are private, and have getters and setters.
The getters are pretty basic:
public function get x():Number{ return _x; }
public function get y():Number{ return _y; }
The setters are where the viewport will be altered, like so:
public function set x(n:Number):void
{
_x = n;
map.x = -(_x + offsetX);
}
public function set y(n:Number):void
{
_y = n;
map.y = -(_y + offsetY);
}
From here, you add your children into the Map container and then can simply go:
map.camera.x = player.x;
map.camera.y = player.y;
Which will cause the player to always be in the centre of the screen.