How I can make multiplayer in ranking system c# in unity - position

my code have no error but ranking position is not working properly
how I change in my project. I want to make RPS in game.

public int currentCheckPoint, lapCount;
public float distance;
private Vector3 checkPoint;
public float counter;
public int rank;
public GameObject panelcar;
public GameObject losepanel;
void Start()
{
currentCheckPoint = 1;
StartCoroutine(LevelFail());
}
// Update is called once per frame
void Update()
{
CalculateDistance();
}
void CalculateDistance()
{
distance = Vector3.Distance(transform.position, checkPoint);
counter = lapCount * 1000 + currentCheckPoint * 100 + distance;
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "CheckPoint")
{
currentCheckPoint = other.GetComponent<CurrentCheckPoint>().currentCheckPointNumber;
checkPoint = GameObject.Find("CheckPoint" + currentCheckPoint).transform.position;
}
if(other.tag == "Finish")
{
if(gameObject.name == "Player")
{
panelcar.SetActive(true);
Time.timeScale = 0f;
AudioListener.volume = 0f;
}
if (gameObject.name == "Red Car" || gameObject.name == "Orrange Car" || gameObject.name == "yellow Car" || gameObject.name == "Blue Car" || gameObject.name == "Tursh Car")
{
losepanel.SetActive(true);
Time.timeScale = 0f;
AudioListener.volume = 0f;
}
}
}

Related

Recycle View Inside Of Fragment Not Calling OnViewCreate

So basically, it's as the title says. I'm implementing a recycle view inside a fragment to create a map on one part of the screen. I need two recycle views on the page but only one isn't working. When I run the debugger in Android Studio it never reaches the override methods in the Adapter class. Below is the code, unfortunately it's a lot.
I should also mention
Number of items is caclulated and is not zero
Adapter is added to recycler view
Layout manager is added to recycler view
Why aren't any of the overriden methods being called?
Please let me know if you require further information
FRAGMENT
public class FragmentMap extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
MapData mapData;
StructureData structures;
public FragmentMap(MapData mapData, StructureData structures)
{
this.mapData = mapData;
this.structures = structures;
}
public FragmentMap() {
// Required empty public constructor
}
public static FragmentMap newInstance(String param1, String param2) {
FragmentMap fragment = new FragmentMap();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
RecyclerView rv = view.findViewById(R.id.mapRecyclerView);
SelectorAdapter myAdapter = new SelectorAdapter(structures);
MapAdapter mapAdapter = new MapAdapter(mapData);
rv.setAdapter(mapAdapter);
rv.setLayoutManager(new GridLayoutManager(
getActivity(),
MapData.HEIGHT,
GridLayoutManager.HORIZONTAL,
false));
return view;
}
}
ADAPTER
public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>{
MapData mapData;
public MapAdapter(MapData mapData)
{
this.mapData = mapData;
}
#NonNull
#Override
public MapViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.grid_cell,parent,false);
MapViewHolder myViewHolder = new MapViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MapViewHolder holder, int position) {
int row = position % MapData.HEIGHT;
int col = position / MapData.HEIGHT;
MapElement mapElement = mapData.get(row, col);
holder.cellOne.setImageResource(mapElement.getNorthEast());
}
#Override
public int getItemCount() {
Log.d("TAG", "getItemCount: " + MapData.HEIGHT * MapData.WIDTH);
return MapData.HEIGHT * MapData.WIDTH;
}
}
VIEWHOLDER
public class MapViewHolder extends RecyclerView.ViewHolder {
ImageView cellOne, cellTwo, cellThree, cellFour, structure;
ConstraintLayout parent;
public MapViewHolder(#NonNull View itemView) {
super(itemView);
cellOne = itemView.findViewById(R.id.imageOne);
cellTwo = itemView.findViewById(R.id.imageTwo);
cellThree = itemView.findViewById(R.id.imageThree);
cellFour = itemView.findViewById(R.id.imageFour);
parent = itemView.findViewById(R.id.parent);
int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
ViewGroup.LayoutParams lp = itemView.getLayoutParams();
lp.width = size;
lp.height = size;
}
}
MAPDATA
public class MapData
{
public static final int WIDTH = 30;
public static final int HEIGHT = 10;
private static final int WATER = R.drawable.ic_water;
private static final int[] GRASS = {R.drawable.ic_grass1, R.drawable.ic_grass2,
R.drawable.ic_grass3, R.drawable.ic_grass4};
private static final Random rng = new Random();
private MapElement[][] grid;
private static MapData instance = null;
public static MapData get()
{
if(instance == null)
{
instance = new MapData(generateGrid());
}
return instance;
}
private static MapElement[][] generateGrid()
{
final int HEIGHT_RANGE = 256;
final int WATER_LEVEL = 112;
final int INLAND_BIAS = 24;
final int AREA_SIZE = 1;
final int SMOOTHING_ITERATIONS = 2;
int[][] heightField = new int[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
heightField[i][j] =
rng.nextInt(HEIGHT_RANGE)
+ INLAND_BIAS * (
Math.min(Math.min(i, j), Math.min(HEIGHT - i - 1, WIDTH - j - 1)) -
Math.min(HEIGHT, WIDTH) / 4);
}
}
int[][] newHf = new int[HEIGHT][WIDTH];
for(int s = 0; s < SMOOTHING_ITERATIONS; s++)
{
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
int areaSize = 0;
int heightSum = 0;
for(int areaI = Math.max(0, i - AREA_SIZE);
areaI < Math.min(HEIGHT, i + AREA_SIZE + 1);
areaI++)
{
for(int areaJ = Math.max(0, j - AREA_SIZE);
areaJ < Math.min(WIDTH, j + AREA_SIZE + 1);
areaJ++)
{
areaSize++;
heightSum += heightField[areaI][areaJ];
}
}
newHf[i][j] = heightSum / areaSize;
}
}
int[][] tmpHf = heightField;
heightField = newHf;
newHf = tmpHf;
}
MapElement[][] grid = new MapElement[HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++)
{
for(int j = 0; j < WIDTH; j++)
{
MapElement element;
if(heightField[i][j] >= WATER_LEVEL)
{
boolean waterN = (i == 0) || (heightField[i - 1][j] < WATER_LEVEL);
boolean waterE = (j == WIDTH - 1) || (heightField[i][j + 1] < WATER_LEVEL);
boolean waterS = (i == HEIGHT - 1) || (heightField[i + 1][j] < WATER_LEVEL);
boolean waterW = (j == 0) || (heightField[i][j - 1] < WATER_LEVEL);
boolean waterNW = (i == 0) || (j == 0) || (heightField[i - 1][j - 1] < WATER_LEVEL);
boolean waterNE = (i == 0) || (j == WIDTH - 1) || (heightField[i - 1][j + 1] < WATER_LEVEL);
boolean waterSW = (i == HEIGHT - 1) || (j == 0) || (heightField[i + 1][j - 1] < WATER_LEVEL);
boolean waterSE = (i == HEIGHT - 1) || (j == WIDTH - 1) || (heightField[i + 1][j + 1] < WATER_LEVEL);
boolean coast = waterN || waterE || waterS || waterW ||
waterNW || waterNE || waterSW || waterSE;
grid[i][j] = new MapElement(
!coast,
choose(waterN, waterW, waterNW,
R.drawable.ic_coast_north, R.drawable.ic_coast_west,
R.drawable.ic_coast_northwest, R.drawable.ic_coast_northwest_concave),
choose(waterN, waterE, waterNE,
R.drawable.ic_coast_north, R.drawable.ic_coast_east,
R.drawable.ic_coast_northeast, R.drawable.ic_coast_northeast_concave),
choose(waterS, waterW, waterSW,
R.drawable.ic_coast_south, R.drawable.ic_coast_west,
R.drawable.ic_coast_southwest, R.drawable.ic_coast_southwest_concave),
choose(waterS, waterE, waterSE,
R.drawable.ic_coast_south, R.drawable.ic_coast_east,
R.drawable.ic_coast_southeast, R.drawable.ic_coast_southeast_concave),
null);
}
else
{
grid[i][j] = new MapElement(
false, WATER, WATER, WATER, WATER, null);
}
}
}
return grid;
}
private static int choose(boolean nsWater, boolean ewWater, boolean diagWater,
int nsCoastId, int ewCoastId, int convexCoastId, int concaveCoastId)
{
int id;
if(nsWater)
{
if(ewWater)
{
id = convexCoastId;
}
else
{
id = nsCoastId;
}
}
else
{
if(ewWater)
{
id = ewCoastId;
}
else if(diagWater)
{
id = concaveCoastId;
}
else
{
id = GRASS[rng.nextInt(GRASS.length)];
}
}
return id;
}
protected MapData(MapElement[][] grid)
{
this.grid = grid;
}
public void regenerate()
{
this.grid = generateGrid();
}
public MapElement get(int i, int j)
{
return grid[i][j];
}
}
MAP ELEMENT
public class MapElement
{
private final boolean buildable;
private final int terrainNorthWest;
private final int terrainSouthWest;
private final int terrainNorthEast;
private final int terrainSouthEast;
private Structure structure;
public MapElement(boolean buildable, int northWest, int northEast,
int southWest, int southEast, Structure structure)
{
this.buildable = buildable;
this.terrainNorthWest = northWest;
this.terrainNorthEast = northEast;
this.terrainSouthWest = southWest;
this.terrainSouthEast = southEast;
this.structure = structure;
}
public boolean isBuildable()
{
return buildable;
}
public int getNorthWest()
{
return terrainNorthWest;
}
public int getSouthWest()
{
return terrainSouthWest;
}
public int getNorthEast()
{
return terrainNorthEast;
}
public int getSouthEast()
{
return terrainSouthEast;
}
/**
* Retrieves the structure built on this map element.
* #return The structure, or null if one is not present.
*/
public Structure getStructure()
{
return structure;
}
public void setStructure(Structure structure)
{
this.structure = structure;
}
}
You are initializing only one RecyclerView in onCreateView, if you want to have two Recyclerviews you just need to initialize second one in the same way.

The bouncing ball under gravity does not stop at bounds

I am making an application and need a ball to bounce under gravity. The ball bounces fine but it never stops.
I tried printing the coordinate of the points where it stopped and what was the velocity. This is the output of one of the cases:
Found it... line 24. (0.00)i + (-0.01)j {14.14(0.79)} (-1.79, 651.57)
So in the ball stopped at height 651.67 while the bound was 600. Here's another case:
Found it... line 24. (0.00)i + (-0.01)j {14.14(0.79)} (-1.79, 1624.58)
Here's the code:
GUI.java
import java.util.Timer;
import java.util.TimerTask;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.stage.Stage;
public class GUI extends Application {
#Override
public void start(Stage theStage) throws Exception {
theStage.setTitle("Bouncy Ball");
Group root = new Group();
Scene theScene = new Scene(root);
theStage.setScene(theScene);
Canvas canvas = new Canvas(750, 600);
root.getChildren().add(canvas);
CircleSprite sprite = new CircleSprite(30, new Point(50, 50));
root.getChildren().add(sprite.image);
sprite.setVelocity(new Vector(new Point(10, 10)));
theStage.show();
theStage.setOnCloseRequest(e -> {
System.exit(0);
});
AnimationTimer gameLoop = new AnimationTimer() {
#Override
public void handle(long now) {
if (sprite.update(new Bounds(700, 600))) {
this.stop();
}
}
};
gameLoop.start();
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Vector velocity = sprite.getVelocity();
velocity.setYComponent(velocity.getYComponent() + 1);
if (Math.abs(sprite.getVelocity().getYComponent()) <= 0.01
&& sprite.getCentre().getY() + 2 * sprite.getRadius() >= 500) {
System.out.println("Found it... line 55");
cancel();
}
}
}, 0, 100);
}
public static void main(String[] args) {
launch(args);
}
}
CircleSprite.java
public class CircleSprite extends Circle {
public javafx.scene.shape.Circle image;
public CircleSprite(long radius, Point centre) {
super(radius, centre);
image = new javafx.scene.shape.Circle(centre.getX(), centre.getY(), radius);
}
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
setCentre(finalPos);
if (finalPos.getX() <= 0 || finalPos.getX() + 2 * getRadius() >= bounds.maxX) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
if (finalPos.getY() <= 0 || finalPos.getY() + 2 * getRadius() >= bounds.maxY) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}
}
Bounds.java
public class Bounds {
public double maxX;
public double maxY;
public Bounds(double maxX, double maxY) {
this.maxX = maxX;
this.maxY = maxY;
}
}
Circle.java
public class Circle extends Shape {
private long radius;
private Point centre;
public Circle(long radius, Point centre) {
this.radius = radius;
this.centre = centre;
this.setVelocity(new Vector(new Point(0.0d, 0.0d), new Point(0, 0)));
this.setMass(0);
this.setRestitution(1);
this.setAcceleration(new Vector(new Point(0, 0), new Point(0, 0)));
}
/*
* Testing for whether or not two circles intersect is very simple: take the
* radii of the two circles and add them together, then check to see if this sum
* is greater than the distance between the two circles.
*/
public boolean isColliding(Circle a, Circle b) {
long dist = a.getRadius() + b.getRadius();
// In general multiplication is a much cheaper operation than taking the square
// root of a value.
return ((dist * dist) < (a.getCentre().getX() - b.getCentre().getX())
* (a.getCentre().getX() - b.getCentre().getX())
+ (a.getCentre().getY() - b.getCentre().getY()) * (a.getCentre().getY() - b.getCentre().getY()));
}
public long getRadius() {
return this.radius;
}
public void setRadius(long radius) {
this.radius = radius;
}
public Point getCentre() {
return this.centre;
}
public void setCentre(Point centre) {
this.centre = centre;
}
}
Shape.java
public class Shape {
private Vector velocity;
private Vector acceleration;
private long mass;
private double invMass;
private float restitution;
public Vector getAcceleration() {
return this.acceleration;
}
public void setAcceleration(Vector acceleration) {
this.acceleration = acceleration;
}
public long getMass() {
return this.mass;
}
public void setMass(long mass) {
this.mass = mass;
this.setInvMass(mass);
}
public Vector getVelocity() {
return this.velocity;
}
public void setVelocity(Vector velocity) {
this.velocity = velocity;
}
public double getInvMass() {
return this.invMass;
}
private void setInvMass(long mass) {
if (mass == 0) {
invMass = Long.MAX_VALUE;
return;
}
this.invMass = 1.0d / (double) mass;
}
public float getRestitution() {
return this.restitution;
}
public void setRestitution(float restitution) {
this.restitution = restitution;
}
}
Vector.java
public class Vector {
private Point p1;
private Point p2;
private double xComponent;
private double yComponent;
private double angle;
private double magnitude;
/*
* The constructor makes a vector crossing through two points p1 and p2.
*
* #param p1 The source point(x1, x2)
*/
public Vector(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
this.xComponent = this.p2.getX() - this.p1.getX();
this.yComponent = this.p2.getY() - this.p1.getY();
this.angle = Math.atan2(this.yComponent, this.xComponent);
this.magnitude = Math.sqrt(this.xComponent * this.xComponent + this.yComponent * this.yComponent);
}
public Vector(Point p2) {
Point p1 = new Point(0, 0);
this.p1 = p1;
this.p2 = p2;
this.xComponent = this.p2.getX() - this.p1.getX();
this.yComponent = this.p2.getY() - this.p1.getY();
this.angle = Math.atan2(this.yComponent, this.xComponent);
this.magnitude = Math.sqrt(this.xComponent * this.xComponent + this.yComponent * this.yComponent);
}
public Vector(double magnitude, Vector unitVector) {
scaledProduct(magnitude, unitVector);
}
private void scaledProduct(double magnitude, Vector unitVector) {
Point point = new Point(magnitude * unitVector.getXComponent(), magnitude * unitVector.getYComponent());
new Vector(point);
}
public static Vector scalarProduct(double magnitude, Vector unitVector) {
Point point = new Point(magnitude * unitVector.getXComponent(), magnitude * unitVector.getYComponent());
return new Vector(point);
}
public static double dotProduct(Vector v1, Vector v2) {
return (v1.xComponent * v2.xComponent + v1.yComponent * v2.yComponent);
}
public static Vector sum(Vector v1, Vector v2) {
return new Vector(new Point(v1.getXComponent() + v2.getXComponent(), v1.getYComponent() + v2.getYComponent()));
}
public static Vector difference(Vector from, Vector vector) {
return new Vector(new Point(from.getXComponent() - vector.getXComponent(),
from.getYComponent() - vector.getYComponent()));
}
public static double angleBetween(Vector v1, Vector v2) {
return Math.acos(Vector.dotProduct(v1, v2) / (v1.getMagnitude() * v2.getMagnitude()));
}
public Point getP1() {
return this.p1;
}
public void setP1(Point p1) {
this.p1 = p1;
}
public Point getP2() {
return this.p2;
}
public void setP2(Point p2) {
this.p2 = p2;
}
public double getXComponent() {
return this.xComponent;
}
public void setXComponent(double d) {
this.xComponent = d;
}
public double getYComponent() {
return this.yComponent;
}
public void setYComponent(double d) {
this.yComponent = d;
}
public double getAngle() {
return this.angle;
}
public void setAngle(double angle) {
this.angle = angle;
}
public double getMagnitude() {
return this.magnitude;
}
public void setMagnitude(double length) {
this.magnitude = length;
}
#Override
public boolean equals(Object v) {
Vector vector = (Vector) v;
return ((this.xComponent == vector.xComponent) && (this.yComponent == vector.yComponent));
}
#Override
public String toString() {
return String.format("(%.2f)i + (%.2f)j {%.2f(%.2f)}", this.xComponent, this.yComponent, this.magnitude,
this.angle);
}
}
Point.java
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public static double distance(Point p1, Point p2) {
return Math.sqrt(
(p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) + (p1.getY() - p2.getY()) * (p1.getY() - p2.getY()));
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return String.format("(%.2f, %.2f)", this.x, this.y);
}
}
What's wrong with the code? I know something is wrong with the exit condition in the GUI.java and CircleSprite.java but can't figure out what. There's two thing that is bothering me:
1. Why is the height out of bound when it stops?
2. Why does the x goes negative?
What happens here is the following (considering x dimension only; same applies to y as well):
The ball passes through the bounds at a speed v. You reverse the speed and decrease its magnitude. This can result in the new velocity not being high enough to get back into the bounds in the next update step and you reverse the velocity again decreasing it even more. This results in the ball moving back and forth in smaller and smaller steps outside of the bounds effectively giving the impression of it stopping.
Example with values:
Frame 1
vx = -16
x = 1
Frame 2
vx = 12
x = -15
Frame 3
vx = -9
x = -3
Frame 4
vx = -6.75
x = -12
...
There are 2 ways of fixing this:
Only update the speed, if the ball is moving in the direction that made it exceede the bounds.
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
setCentre(finalPos);
if ((finalPos.getX() <= 0 && velocity.getXComponent() < 0) || (finalPos.getX() + 2 * getRadius() >= bounds.maxX && velocity.getXComponent() > 0)) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
if ((finalPos.getY() <= 0 && velocity.getYComponent() < 0) || (finalPos.getY() + 2 * getRadius() >= bounds.maxY && velocity.getYComponent() > 0)) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}
Prevent the ball from ending up outside of the bounds in the first place
public boolean update(Bounds bounds) {
Point pos = this.getCentre();
Vector velocity = this.getVelocity();
Point finalPos = new Point(pos.getX() + velocity.getXComponent(), pos.getY() + velocity.getYComponent());
boolean invertX = true;
if (finalPos.getX() <= 0) {
// mirror on left
finalPos.setX(-finalPos.getX());
} else if (finalPos.getX() + 2 * getRadius() >= bounds.maxX) {
// mirror on right
finalPos.setX(2 * (bounds.maxX - 2 * getRadius()) - finalPos.getX());
} else {
invertX = false;
}
if (invertX) {
velocity.setXComponent(velocity.getXComponent() * (-1) * 0.75);
}
boolean invertY = true;
if (finalPos.getY() <= 0) {
// mirror on top
finalPos.setY(-finalPos.getY());
} else if (finalPos.getY() + 2 * getRadius() >= bounds.maxY) {
// mirror on bottom
finalPos.setY(2 * (bounds.maxY - 2 * getRadius()) - finalPos.getY());
} else {
invertY = false;
}
if (invertY) {
velocity.setYComponent(velocity.getYComponent() * (-1) * 0.75);
}
setCentre(finalPos);
image.setLayoutX(finalPos.getX());
image.setLayoutY(finalPos.getY());
if (Math.abs(velocity.getYComponent()) <= 0.01 && getCentre().getY() + 2 * getRadius() >= bounds.maxY) {
System.out.println("Found it... line 24" + velocity + " " + getCentre());
return true;
}
return false;
}

NullPointerException not in my code but in onResume() for LibGDX AndroidInput

This the stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.epl.game, PID: 18789
java.lang.RuntimeException: Unable to resume activity {com.epl.game/com.epl.game.AndroidLauncher}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.badlogic.gdx.backends.android.AndroidInput.onResume()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4205)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.badlogic.gdx.backends.android.AndroidInput.onResume()' on a null object reference
at com.badlogic.gdx.backends.android.AndroidApplication.onResume(AndroidApplication.java:300)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1453)
at android.app.Activity.performResume(Activity.java:7962)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4195)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237) 
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:49 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
This is my main project
package com.epl.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import org.omg.PortableServer.POAManagerPackage.State;
import java.util.ArrayList;
import java.util.Random;
public class epl extends ApplicationAdapter {
MyTextInputListener listener = new MyTextInputListener();
SpriteBatch batch;
Texture background;
Texture[] man;
State[] gsm;
int batsmanState = 0;
int pause = 0;
float gravity = 0.2f;
float velocity = 0;
int manY = 0;
Rectangle manRectangle;
BitmapFont font1;
BitmapFont font2;
BitmapFont font3;
Texture dizzy;
int score = 0;
int gameState = 0;
int i1 = 0;
int i2 = 0;
State state0;
State state1;
State state2;
State state3;
State state4;
State state5;
Random random;
String humanName;
ArrayList<Integer> coinXs = new ArrayList<>();
ArrayList<Integer> coinYs = new ArrayList<>();
ArrayList<Rectangle> coinRectangles = new ArrayList<>();
Texture coin;
int coinCount;
ArrayList<Integer> bombXs = new ArrayList<>();
ArrayList<Integer> bombYs = new ArrayList<>();
ArrayList<Rectangle> bombRectangles = new ArrayList<>();
Texture bomb;
int bombCount;
PlayServices ply;
#Override
public void create() {
batch = new SpriteBatch();
background = new Texture("bg.png");
man = new Texture[4];
man[0] = new Texture("batsman.jpg");
man[1] = new Texture("batsman.jpg");
man[2] = new Texture("batsman.jpg");
man[3] = new Texture("batsman.jpg");
gsm = new State[6];
gsm[0] = (state0);
gsm[1] = (state1);
gsm[2] = (state2);
gsm[3] = (state3);
gsm[4] = (state4);
gsm[5] = (state5);
manY = Gdx.graphics.getHeight() / 2;
coin = new Texture("ball.png");
bomb = new Texture("stump.jpeg");
random = new Random();
dizzy = new Texture("out.jpeg");
font1 = new BitmapFont();
font1.setColor(Color.RED);
font1.getData().setScale(10);
font2 = new BitmapFont();
font2.setColor(Color.RED);
font2.getData().setScale(10);
font3 = new BitmapFont();
font3.setColor(Color.RED);
font3.getData().setScale(10);
}
public void makeCoin() {
float height = random.nextFloat() * Gdx.graphics.getHeight();
coinYs.add((int) height);
coinXs.add(Gdx.graphics.getWidth());
}
public void makeBomb() {
float height = random.nextFloat() * Gdx.graphics.getHeight();
bombYs.add((int)height);
bombXs.add(Gdx.graphics.getWidth());
}
private String myText;
public class MyTextInputListener implements Input.TextInputListener {
#Override
public void input(String text) {
}
#Override
public void canceled() {
whatIsYourName();
}
public String getText() {
return myText;
}
public void whatIsYourName() {
Gdx.input.getTextInput(listener, "Name : ", "", "eg:Jonathan");
humanName = listener.getText();
gameState = 1;
}
}
public epl(PlayServices ply){
this.ply = ply;
}
#Override
public void render () {
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
if (gameState == 1 && state1 == null) {
// GAME IS LIVE
// BOMB
if (bombCount < 250) {
bombCount++;
} else {
bombCount = 0;
makeBomb();
}
bombRectangles.clear();
for (int i = 0; i < bombXs.size(); i++) {
batch.draw(bomb, bombXs.get(i), bombYs.get(i));
bombXs.set(i, bombXs.get(i) - 8);
bombRectangles.add(new Rectangle(bombXs.get(i),
bombYs.get(i),
bomb.getWidth(), bomb.getHeight()));
}
// COINS
if (coinCount < 100) {
coinCount++;
} else {
coinCount = 0;
makeCoin();
}
coinRectangles.clear();
for (int i = 0; i < coinXs.size(); i++) {
batch.draw(coin, coinXs.get(i), coinYs.get(i));
coinXs.set(i, coinXs.get(i) - 4);
coinRectangles.add(new Rectangle(coinXs.get(i),
coinYs.get(i),
coin.getWidth(), coin.getHeight()));
}
if (Gdx.input.justTouched()) {
velocity = -10;
}
if (pause < 8) {
pause++;
} else {
pause = 0;
if (batsmanState < 3) {
batsmanState++;
} else {
batsmanState = 0;
}
}
velocity += gravity;
manY -= velocity;
if (manY <= 0) {
manY = 0;
}
} else if (gameState == 5 && state5 == null) {
//leaderboard
if (Gdx.input.justTouched()){
ply.submitScore(humanName,score);
ply.showScore(humanName);
gameState = 1;
}
}else if (gameState == 3 && state3 == null) {
//name
listener.whatIsYourName();
gameState = 1;
} else if (gameState == 0 && state0 == null) {
// Waiting to start
if (humanName == null){
gameState = 3;
}else{
gameState = 1;
}
} else if (gameState == 4 && state4 == null) {
//final score display
font3.draw(batch, "Score = " + score,100,1400);
if (Gdx.input.justTouched()){
score = 0;
gameState = 1;
}
}else if (gameState == 2 && state2 == null) {
// GAME OVER
if (Gdx.input.justTouched()) {
manY = Gdx.graphics.getHeight() / 2;
velocity = 0;
coinXs.clear();
coinYs.clear();
coinRectangles.clear();
coinCount = 0;
bombXs.clear();
bombYs.clear();
bombRectangles.clear();
bombCount = 0;
i1 = 0;
i2 = 0;
}
}
if (gameState == 2) {
batch.draw(dizzy, Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY);
if (Gdx.input.justTouched()){
gameState = 4;
}
} else {
batch.draw(man[batsmanState], Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY);
}
manRectangle = new Rectangle(Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY,
man[batsmanState].getWidth(), man[batsmanState].getHeight());
for (int i=0; i < coinRectangles.size();i++) {
if (Intersector.overlaps(manRectangle, coinRectangles.get(i))) {
score++;
i1 = random.nextInt((4 -1) + 1);
score = score + i1;
i2 = i1 + 1;
coinRectangles.remove(i);
coinXs.remove(i);
coinYs.remove(i);
break;
}
}
for (int i=0; i < bombRectangles.size();i++) {
if (Intersector.overlaps(manRectangle, bombRectangles.get(i))) {
gameState = 2;
}
}
font1.draw(batch, String.valueOf(score),100,200);
font2.draw(batch, String.valueOf(i2),900,200);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
}
}
This is my android launcher
package com.epl.game;
import android.content.Intent;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
public class AndroidLauncher extends AndroidApplication implements PlayServices {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
gameHelper.enableDebugLog(true);
GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener() {
#Override
public void onSignInFailed() {
}
#Override
public void onSignInSucceeded() {
}
};
gameHelper.setup(gameHelperListener);
}
String leaderboard = "CgkI7PuNlqsVEAIQAA";
private GameHelper gameHelper;
#Override
protected void onStart() {
super.onStart();
gameHelper.onStart(this); // You will be logged in to google play services as soon as you open app , i,e on start
}
#Override
protected void onStop() {
super.onStop();
gameHelper.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
gameHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean signIn() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
gameHelper.beginUserInitiatedSignIn();
}
});
} catch (Exception e) {
}
return true;
}
#Override
public void submitScore(String LeaderBoard, int highScore) {
if (isSignedIn()) {
Games.Leaderboards.submitScore(gameHelper.getApiClient(), LeaderBoard, highScore);
} else {
System.out.println(" Not signin Yet ");
}
}
#Override
public void showScore(String leaderboard) {
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), leaderboard), 1);
} else {
signIn();
}
}
#Override
public boolean isSignedIn() {
return false;
}
And this is my play services interface
package com.epl.game;
public interface PlayServices
{
boolean signIn();
void submitScore(String LeaderBoard, int highScore);
void showScore(String LeaderBoard);
boolean isSignedIn();
}
I am new to libgdx and I am trying to create a game with a leaderboard .
I created this by importing the BaseGameUtils .
Else if you have another way i could create a global leaderboard in my
game please let me know.
It is critical that you call the initialize method in onCreate of your AndroidLauncher class. This is what sets up LibGDX's backends for graphics, sound, and input. Since you did not call initialize, the input class (along with graphics, sound, files, etc.) was not set up and assigned, and so is still null when the resume part of the lifecycle is reached. This leads to the NullPointerException.
In your case, your onCreate method should look something like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// customize the configuration here
initialize(new epl(), config);
// Your other setup code...
}
Note, class names in Java should always start with a capital letter. It will make it easier to read and understand your code.

Progressive lag with each collision iteration libGDX

Hello I am developing a game on my spare time with AIDE and libGDX. Though AIDE has some missing methods of the libGDX API and I had to create some workarounds to compensate for the missing methods.
So my problem is that with every instance of a collision the app becomes more and more laggy. No new textures are being drawn and non go away. Just a poor implementation that is meant to push you out of said collision tile. It runs fine until you have a few collisions. My thought is that it creates a new variable with every collision and stores it into memory causing a leak. But I can't really tell if that is the case. Oh I'd like to add that I don't have access to a computer, just my phone. Here is my movement class
move.java
public class move
{
float posX;
float posY;
float touchedOnScreenX;
float touchedOnScreenY;
float centerOfScreenX;
float centerOfScreenY;
float posXSetter;
float posYSetter;
float Speed = 150;
float mapBoundsWidth;
float mapBoundsHeight;
boolean upperBounds;
boolean lowerBounds;
boolean rightBounds;
boolean leftBounds;
boolean tileCollition;
public move() {
}
public void renderMove(float delta) {
if(Gdx.input.isTouched()) {
screenAndTouchInfo();
checkBoundsBoolean();
checkForCollision();
}
}
//slows game down
private void checkForCollision()
{
if (upperBounds == false)
{
if (lowerBounds == false)
{
if (rightBounds == false)
{
if (leftBounds == false)
{
if (tileCollition == false)
{
movement();
}
else
{
collitionSide();
}
}
else
{
posX++;
}
}
else
{
posX--;
}
}
else
{
posY++;
}
}
else
{
posY --;
}
}
private void movement()
{
posYSetter = posY;
posXSetter = posX;
if (touchedOnScreenX < centerOfScreenX)
{
posX -= Gdx.graphics.getDeltaTime() * Speed;
}
else
{
posX += Gdx.graphics.getDeltaTime() * Speed;
}
if (touchedOnScreenY < centerOfScreenY)
{
posY -= Gdx.graphics.getDeltaTime() * Speed;
}
else
{
posY += Gdx.graphics.getDeltaTime() * Speed;
}
if (touchedOnScreenY < centerOfScreenY + 64 && touchedOnScreenY > centerOfScreenY - 64)
{
posY = posYSetter;
}
if (touchedOnScreenX < centerOfScreenX + 64 && touchedOnScreenX > centerOfScreenX - 64)
{
posX = posXSetter;
}
}
//buggy and slows game down. Can push you into tile if input is the opposite of the side
public void collitionSide() {
if (tileCollition == true){
if (touchedOnScreenX < centerOfScreenX)
{
posX = posX +10;
}
else
{
posX = posX - 10;
}
if (touchedOnScreenY < centerOfScreenY)
{
posY = posY +10;
}
else
{
posY = posY -10;
}
}
}
private void screenAndTouchInfo()
{
touchedOnScreenX = Gdx.input.getX();
touchedOnScreenY = (Gdx.graphics.getHeight() - Gdx.input.getY());
centerOfScreenX = Gdx.graphics.getWidth() / 2;
centerOfScreenY = Gdx.graphics.getHeight() / 2;
}
//slows game down
private void checkBoundsBoolean()
{
if (posX > mapBoundsWidth)
{
rightBounds = true;
}
else {
rightBounds = false;
}
if (posY > mapBoundsHeight)
{
upperBounds = true;
}
else {
upperBounds = false;
}
if (posX < mapBoundsWidth - mapBoundsWidth)
{
leftBounds = true;
}
else {
leftBounds = false;
}
if (posY < mapBoundsHeight - mapBoundsHeight)
{
lowerBounds = true;
}
else {
lowerBounds = false;
}
}
public void setTileCollision(boolean tileCollision) {
this.tileCollition = tileCollision;
}
public float getPosX() {
return posX;
}
public float getPosY() {
return posY;
}
public float getTouchedOnScreenX() {
return touchedOnScreenX;
}
public float getTouchedOnScreenY() {
return touchedOnScreenY;
}
public float getCenterOfScreenX() {
return centerOfScreenX;
}
public float getCenterOfScreenY() {
return centerOfScreenY;
}
public void setMapboundsWidth(float width) {
this.mapBoundsWidth = width;
}
public void setMapboundsHeight(float height) {
this.mapBoundsHeight = height;
}
}
I know that is a lot of code to comb through and I am sorry if it isn't always clear what is going on. I refactored it to where it would be a little easier to understand. Oh if anyone could tell me why AIDE is missing some methods of libGDX that would be nice too.The most notable one would be Cell.setTile(). That I know is in libGDX's API and can be found in their documentation. But when I implement it it throws a unknown method of class Cell error. I have researched on how to use the method as well with no avail. Had to create int[][] map and a for loop to draw map with another Texture[]. It works. Lol. Thank you to whomever even took the time to look at my long winded double question. Hopefully someone can tell me why this lag is created from said collisions.
I recommend moving your collision code into a separate thread. This should improve performance significantly:
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
#Override
public void run() {
// Physics loop goes here
}
});
Make sure to shutdown the executor when disposing your screen.

JavaFX: Massive collision detection optimization (Quad Tree)

I was working on massive collision detection for my game(more than 1000 sprites is massive for my game), and i was searching to find a way to implement this, then i reached to quad tree:
http://en.wikipedia.org/wiki/Quadtree
Well it's approach to reduce the number of objects that should be check for collision by dividing them to the groups of objects which have more chance to collide.
I found a java version of quad tree here:
http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
Then i change it and use it for my javafx game. but the performance wasn't really good for huge number of objects, so i made some optimisation on it.
Well i used AnimationTimer for each tree to check for collisions which has improved performance so much. i think Animation Timer use GPU to process because when i run my code CPU usage doesn't go hight(3% to 5% - 1640 sprites). but if i use Thread instead of AnimationTimer it use much more CPU(about 40% to 50% - 1640 sprites).
import java.util.ArrayList;
import java.util.List;
import javafx.animation.AnimationTimer;
import javafx.scene.layout.Region;
import javafx.scene.layout.RegionBuilder;
import javafx.scene.paint.Color;
import viwofx.sprit.Sprite;
import viwofx.ui.GameScene;
public class QuadTree
{
private int MAX_OBJECTS = 10;
private int MAX_LEVELS = 5;
private int level;
private ArrayList<Sprite> sprites;
private ArrayList<Sprite> unAllocatedSprites;
private Region bounds;
private QuadTree[] nodes;
private QuadTree parent;
private AnimationTimer detection;
private boolean detecting = false;
private QuadTree getqt()
{
return this;
}
public QuadTree(QuadTree p, int pLevel, Region pBounds)
{
this.parent = p;
level = pLevel;
sprites = new ArrayList<>(0);
unAllocatedSprites = new ArrayList<>(0);
bounds = pBounds;
nodes = new QuadTree[4];
detection = new AnimationTimer()
{
#Override
public void handle(long l)
{
// This for happens when this node has child nodes and there is some object which can not fit whitin the bounds of child nodes
// these object being checked till they can fit inside the bounds of child nodes then they will be added to correspinding child node,
// or object is out of bounds then it will be pushed to the parent node
for (int i = 0; i < unAllocatedSprites.size(); i++)
{
if (!isInside(unAllocatedSprites.get(i)))
{
pushToParent(unAllocatedSprites.get(i));
continue;
}
int index = getIndex(unAllocatedSprites.get(i));
if (index != -1)
{
nodes[index].add(unAllocatedSprites.remove(i));
}
}
for (int i = 0; i < sprites.size(); i++)
{
Sprite ts = sprites.get(i);
if (isInside(ts))
{
int ii = 0;
for (ii = 0; ii < sprites.size(); ii++)
{
Sprite ts2 = sprites.get(ii);
if (ts != ts2)
{
Your collision detection logic
}
}
if (parent != null)
{
for (ii = 0; ii < parent.getUnAllocatedSprites().size(); ii++)
{
Sprite ts2 = parent.getUnAllocatedSprites().get(ii);
if (ts != ts2 && isInside(ts2))
{
Your collision detection logic
}
}
}
}
else
{
pushToParent(ts);
}
}
}
};
}
public int getLevel()
{
return level;
}
public ArrayList<Sprite> getUnAllocatedSprites()
{
return unAllocatedSprites;
}
// Split the node into 4 subnodes
private void split()
{
double subWidth = (bounds.getPrefWidth() / 2);
double subHeight = (bounds.getPrefHeight() / 2);
double x = bounds.getLayoutX();
double y = bounds.getLayoutY();
nodes[0] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x).layoutY(y).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[1] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x + subWidth).layoutY(y).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[2] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x).layoutY(y + subHeight).prefWidth(subWidth).prefHeight(subHeight).build());
nodes[3] = new QuadTree(this, level + 1, RegionBuilder.create().layoutX(x + subWidth).layoutY(y + subHeight).prefWidth(subWidth).prefHeight(subHeight).build());
}
private int getIndex(Sprite s)
{
int index = -1;
double verticalMidpoint = bounds.getLayoutX() + (bounds.getPrefWidth() / 2);
double horizontalMidpoint = bounds.getLayoutY() + (bounds.getPrefHeight() / 2);
double spriteMaxX = (s.getNode().getTranslateX() + s.getWidth());
double spriteMaxY = (s.getNode().getTranslateY() + s.getHeight());
// Object can completely fit within the top quadrants
boolean topQuadrant = (spriteMaxY < horizontalMidpoint);
// Object can completely fit within the bottom quadrants
boolean bottomQuadrant = (s.getNode().getTranslateY() >= horizontalMidpoint);
// Object can completely fit within the left quadrants
if (s.getNode().getTranslateX() >= bounds.getLayoutX() && spriteMaxX < verticalMidpoint)
{
if (topQuadrant)
{
index = 0;
}
else if (bottomQuadrant)
{
index = 2;
}
}
// Object can completely fit within the right quadrants
else if (s.getNode().getTranslateX() >= verticalMidpoint && (s.getNode().getTranslateX() + s.getWidth()) < (bounds.getLayoutX() + bounds.getPrefWidth()))
{
if (topQuadrant)
{
index = 1;
}
else if (bottomQuadrant)
{
index = 3;
}
}
return index;
}
public boolean isInside(Sprite s)
{
double maxX = bounds.getLayoutX() + bounds.getPrefWidth();
double maxY = bounds.getLayoutY() + bounds.getPrefHeight();
// Object can completely fit within the left quadrants
if (s.getNode().getTranslateX() >= bounds.getLayoutX() && (s.getNode().getTranslateX() + s.getWidth()) < maxX && s.getNode().getTranslateY() >= bounds.getLayoutY() && (s.getNode().getTranslateY() + s.getHeight()) < maxY)
{
return true;
}
if (parent != null && parent.getUnAllocatedSprites().contains(s))
{
return true;
}
return false;
}
public void pushToParent(Sprite s)
{
sprites.remove(s);
unAllocatedSprites.remove(s);
if (parent == null)
{
//System.out.println("parent");
if (!unAllocatedSprites.contains(s))
{
unAllocatedSprites.add(s);
}
return;
}
parent.add(s);
if (sprites.size() < 1 && unAllocatedSprites.size() < 1)
{
stopDetection();
}
}
public void add(viwofx.sprit.Sprite sprite)
{
// if sprite is not fit in the bounds of node, it will be pushed to the parent node.
// this is a optimization for when child node push a object to this node and object still is not fit in the bounds this node,
// so it will be pushed to the parent node till object can be fited whitin the node bounds
// this if prevent of out of bounds object to being added to unAllocatedSprites and then being pushed to parent
if (!isInside(sprite))
{
pushToParent(sprite);
return;
}
// if tree has been splited already add sprite to corrosponding child
if (nodes[0] != null)
{
int index = getIndex(sprite);
if (index != -1)
{
nodes[index].add(sprite);
return;
}
else
{
unAllocatedSprites.add(sprite);
return;
}
}
sprites.add(sprite);
if (!detecting)
{
startDetection();
}
if (sprites.size() > MAX_OBJECTS && level < MAX_LEVELS)
{
if (nodes[0] == null)
{
split();
}
int i = 0;
while (i < sprites.size())
{
int index = getIndex(sprites.get(i));
if (index != -1)
{
nodes[index].add(sprites.remove(i));
}
else
{
unAllocatedSprites.add(sprites.remove(i));
}
}
}
}
public List<Sprite> retrieve(List<Sprite> returnObjects, Sprite pRect)
{
int index = getIndex(pRect);
if (index != -1 && nodes[0] != null)
{
nodes[index].retrieve(returnObjects, pRect);
}
returnObjects.addAll(sprites);
return returnObjects;
}
public void startDetection()
{
detecting = true;
detection.start();
}
public void stopDetection()
{
//detecting = false;
//detection.stop();
}
}
I hope this will be helpful for you.

Resources