How to use Box2D sensor contact to increment an integer variable? - android

Firstly, thanks for your time.
How do I use Box2D Sensors on the EdgeShape(s) to determine a collision condition with the Ball, then use said condition to increment a score variable?
I am creating a Pong clone using Box2D via libGDX! I have found great examples and tutorials from iforce2d and Ray Wenderlich, however, they are written in languages and libraries that I am not familiar with at the moment. Trying to comprehend and convert the code is not working for me. If code or a link to a Java/libGDX rendition of Sensor use could be provided, I would be much obliged.
I am receiving contacts in my code, but I do not yet understand the recipe for the algorithm that would ignore contact with the paddle rectangles and arena boundary, but increment a score variable upon collision with the left or right EdgdeShape sensors.
I have scavenged the web for two weeks in an effort to find bits and pieces of useful information to hack together a solution before posting to SO, however, I am officially stumped on this one. I could use some guidance.

i don't know how far you came with your efforts and never worked with libgdx, but the way to go is something like this:
fixture.setUserData() (could be body) to recognize the single bodies you have (outLeft, outRight, paddleLeft, paddleRight, ball) - this could be any useful information from Integers to the whole game object instance, what ever you need
set your left/right boundaries as sensor fixture.setSensor(true) - afaik this has to be set to not let the boundaries induct a collision
implement your contact listeners endContact(Contact contact) (or begin contact, like you want it) call and request the fixtures A and B from the contact object with contact.getFixtureA/B() and determine if the given collision is relevant for your needs e.g.:
-
public void endContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Object userDataA = fixtureA.getBody().getUserData();
Object userDataB = fixtureB.getBody().getUserData();
// check if one is ball
if (userDataA instanceof Ball) {
checkBallCollision(userDataB);
} else if (userDataB instanceof Ball) {
checkBallCollision(userDataA);
}
}
private void checkBallCollision(Object userData) {
if (userData instanceof outLeft) {
//add points to right player
} else if (userData instanceof outRight) {
//add points to left player
}
}
-4. add your ContactListener to your World.setContactListener()
as said, i'm not 100% sure that this will work, never used it in libgdx, just some smaller experiments with andengines box2d extension, but in fact it should be the same for both engines. here is another link handling sensors in andengine: http://www.matim-dev.com/creating-sensors.html

Related

How to improve Android MVVM Tic-Tac-Toe

I was following this tutorial (https://academy.realm.io/posts/eric-maxwell-mvc-mvp-and-mvvm-on-android/) implementing different patterns (MVC, MVP and MVVM) in Kotlin for a Tic Tac Toe game. At the MVVM part, the example does the following:
public class TicTacToeViewModel implements ViewModel {
private Board model;
public final ObservableArrayMap<String, String> cells = new ObservableArrayMap<>();
public final ObservableField<String> winner = new ObservableField<>();
public TicTacToeViewModel() {
model = new Board();
}
[...]
public void onClickedCellAt(int row, int col) {
Player playerThatMoved = model.mark(row, col);
cells.put("" + row + col, playerThatMoved == null ?
null : playerThatMoved.toString());
winner.set(model.getWinner() == null ? null : model.getWinner().toString());
}
[...]
}
Considering that the model, of class Board, already has an attribute board (that is an Array < Array < Cell > >), what's the point for replicate that board with other variable at the TicTacToeViewModel? Is not possible refer to the model board directly with an LiveData or Observable class? Same for the winner
I've saw as well many implementations on Github doing the same, and I am wondering if that's happening due to heritance of the article or in fact has to be this way when the data is kind of complex (a 2D array in this particular case)
I'll appreciate any comments or thoughts on this. Thanks in advance!
I skimmed the tutorial and the github page, and in short I would recommend not following that tutorial :)
Looking at the source code on github, it's clearly an unfinished project. For example, the one layout in the entire project just has a "Hello, world!" TextView in it, which is boilerplate code you get just for creating an Android project...
But to answer your question in a more general sense, you don't necessarily need redundant data structures to represent the board. One reason you might want them is to differentiate between what is displayed to the user versus what the app uses to track the state of the game. For example, the user sees 'O's and 'X's, but perhaps your ViewModel or backing data structure tracks the board as a binary string for the sake of memory and performance (imagine scaling the game out to a much larger board.) But you could probably just create a function to convert the underlying data to a user-friendly format for display, without the need for redundant data structures.

Synchronized charts or multiple charts like Highcharts in Android

How could we achieve Synchronized charts in Android.
For my web page I've used Highcharts API. Is there any similar thing for Android. I've checked various libraries mentioned here but didn't find any which will match the requirement.
I don't want combined charts like this and this. I'm looking for Synchronized charts.
Is there any library which will meet the requirement or Should I go with webView (It's a worst case for me)
Is it possible with MPAndroidChart?
EDIT:
Resultant chart should be like the Charts given in highcharts page
Sample:
UPDATE
Motto is not just to draw the 3 charts. The Aim is to synchronize them. Synchronise means all the 3 charts have same x-axis(values), on click at any point in these charts the plot at that particular point should be highlighted in all the charts. I'm sure I didn't explain it properly. Kindly check this link and hover the graph
when clicked on chart 1 get the X and Y points and highlight them on chart 2. Same with 2nd chart.
lineChart1.setOnChartValueSelectedListener(new OnChartValueSelectedListener()
{
#Override
public void onValueSelected(Entry e, Highlight h)
{
lineChart2.highlightValue(e.getX(),e.getY(),0,false);
}
#Override
public void onNothingSelected()
{
}
});
lineChart2.setOnChartValueSelectedListener(new OnChartValueSelectedListener()
{
#Override
public void onValueSelected(Entry e, Highlight h)
{
lineChart1.highlightValue(e.getX(),e.getY(),0,false);
}
#Override
public void onNothingSelected() {
}
});
NOTE set the last argument to false so that it doesn't call the listener again and again. If this is not set then it results to deadlock.
The sample app has a good display of the features available to you "out of the box" with MPAndroidChart.
As you can see, there is an example of multiple charts inside a ListView which seems to be close to your requirement.
Likewise, the source code is available on GitHub for you to inspect and see if it has the available classes and methods for you to do what you want out of the box.
At the same time, you should understand that it is often unrealistic to expect to find a library that will exactly suit an unusual requirement from mere configuration alone. Free and open source libraries often provision for extension and customisation and MPAndroidChart is no exception. As a professional software engineer, or as an aspiring one, you should be willing and prepared to program that yourself.
In your particular case, it seems you want some kind of co-ordination between the charts. So if you click on one of them then the MarkerView appears on all at the same xIndex in the DataSet.
To attempt this, you would start by looking at the code for OnChartGestureListener. A solution can be obtained through using event-driven programming. You would set up 3 implementations of OnChartGestureListener which would use events to transmit the current gesture to a mediator who then triggers the same gestures on the other two charts. For example, inside OnChartGestureListener there is a method to implement called:
void onChartScale(MotionEvent var1, float var2, float var3);
Your implementation would look something like this:
#Override
void onChartScale(MotionEvent var1, float var2, float var3) {
//transmit event to mediator
//handle event for this chart
}
If this is too difficult then you will have to stick with Highcharts inside a WebView as you have cogently suggested yourself. However, be aware that the performance inside the WebView will not be as good as using a library that renders to canvas directly.
In short, it is possible, although difficult, to accomplish what you want using MPAndroidChart and no "out-of-the-box" solution is available.
You can surely make it using MPAndroidCharts library.
Go for 1> LineChart (with legend, simple design) for Speed
2> LineChart (cubic lines) / (gradient fill) for Elevation , Heart
While Using gradientFill apply this to eliminate dashed line and draw a straight line:
lineDataSet.enableDashedLine(0f, 0f, 0f);
lineDataSet.enableDashedHighlightLine(0f, 0f, 0f);

libgdx - how to handle time-dependent events?

I'm starting to develop a game in libgdx, and I'm wondering what the best practice is for the following situation. There are two things that I'm trying to do at the moment: move a menu (sprite) into place, and pan the camera to the player sprite. My idea to accomplish these things is to have an 'action_stack' ArrayList in the render() function. The ArrayList would contain 'Action' instances. Each Action instance would have a step() function, which would be over-ridden. In the render() function, I would iterate through action_stack, and fire each elements' step() function. So, to accomplish moving the menu into place, I would create the class:
public class MenuAnim1 implements Action {
private int targetX;
private int targetY;
private Sprite menu;
public MenuAnim1() {
//set initial sprite and position
}
public Step() (
//move this.menu towards targetX and targetY
//draw the sprite
//if not at target position, do nothing
//if at target position, remove this object from action_stack
}
}
...and put an instance into the action_stack:
MenuAnim1 menuAnim1 = new MenuAnim1();
action_stack.add(menuAnim1);
Sorry if my Java is bad, I'm not super familiar with it. Anyways, my question is: is this even good practice? What do people normally do? Is there a better way to do what I'm describing above?
I have never used Actions, but your idea is good. If you want them to be time dependant (and thus fps independant), be sure to use the time that has passed since the last frame to the current, also known as delta or deltaTime. You can get it like this:
Gdx.graphics.getDeltaTime();
so, to make your action move the sprite, for example, to the right, this would do the trick:
speed = 10; //It will move 10 units per second.
delta = Gdx.graphics.getDeltaTime();
menu.translateX(speed*delta);
(Sprite#translateX)

Android, how to redraw the points with same time difference as in drawing canvas?

On developing a painting canvas application in android, i need to track all the points and have to redraw it in another canvas. Now i am able to track all the points, but don't know how to synchronize the point drawing in case of draw and redraw ie the user should redraw the points at the same time gap as in the draw. How can i achieve this?
Not sure if this is the sort of answer you are looking for but I would record the events with a sort of timestamp, really a time difference to the next point. Something like:
class Point {
int x;
int y;
long deltaTime;
}
Its up to you how precise you want to be with the timing. Second to millisecond precision should be good enough. You could interpret deltaTime as either the time until this point should be drawn or the time until the next point should be drawn (I'm going to use the latter in my example).
A few reasons to use a deltaTime instead of a direct timestamp is that it lets you check for really long pauses and you are going to have to compute the delta time anyways in playback. Also using it as a long should give you enough room for really lengthy pauses and lets you use the Handler class which accepts a long integer for the number of milliseconds to wait before executing.
public class Redrawer implements Handler.callback {
LinkedList<Point> points; //List of point objects describing your drawing
Handler handler = new Handler(this); //Probably should place this in class initialization code
static final int MSG_DRAW_NEXT = 0;
public void begin(){
//Do any prep work here and then we can cheat and mimic a message call
//Without a delay specified it will be called ASAP but on another
//thread
handler.sendEmptyMessage(MSG_DRAW_NEXT);
}
public boolean handleMessage(Message msg){
//If you use the handler for other things you will want to
//branch off depending on msg.what
Point p = points.remove(); //returns the first element, and removes it from the list
drawPoint(p);
if (!points.isEmpty())
handler.sendEmptyMessageDelayed(MSG_DRAW_NEXT, p.deltaTime);
public void drawPoint(Point p){
//Canvas drawing code here
//something like canvas.drawPixel(p.x, p.y, SOMECOLOR);
//too lazy to look up the details right now
//also since this is called on another thread you might want to use
//view.postInvalidate
}
This code is far from complete or bullet-proof. Namely you will need to possibly pause or restart the redrawing at a later time because the user switched activities or got a phone call, etc. I also didn't implement the details of where or how you get the canvas object (I figure you have that part down by now). Also you probably want to keep track of the previous point so you can make a rectangle to send to View.postInvalidate as redrawing a small portion of the screen is much faster than redrawing it all. Lastly I didn't implement any clean-up, the handler and points list will need to be destroyed as needed.
There are probably several different approaches to this, some probably better than this. If you're worried about long pauses between touch events simply add a check for the deltaTime if its greater than say 10 seconds, then just override it to 10 seconds. Ex. handler.sendEmptyMessage(MSG_DRAW_NEXT, Math.min(p.deltaTime, 100000)); I'd suggest using a constant instead of a hard coded number however.
Hope this helps

How do i make a history calculator in android?

I am making a calculator same as windows calculator. I am stuck at the history feature. which would be the best UI control to implement the history feature as seen in Windows Calculator?
I also want onclick events on the history.
I'm not sure how you represent a calculation, but you could have a simple class like this:
enum Operator {PLUS,MINUS,DIV,MULT};
class Calculation {
float operand1,operand2;
Operator operator;
public Calculation(float op1,float op2,Operator operator){
this.operand1=op1;
this.operand1=op2;
this.operator=operator;
}
}
Then when a calculation is done, create an object of this type and add it to an ArrayList:
List<Calculation> history = new ArrayList<Calculation>();// history
history.add(new Calculation(5,5,Operator.PLUS));// add a new `Calculation` to our list
Then access the list with history.get(some_integer), based on your UI.
Could you just use a List containing a number of previously entered calculations? If you knew the maximum possible history size in advance, you could just stick with a normal array, but a List will give you more flexibility.
You need to store all the operations and results with an index here. Increase the index every time when you perform an operation.To retrieve the past operation, manipulate the index and you can get the values.You can use Collection API for storing the operations.

Categories

Resources