When I try to blend Rectangles in javafx it works only in 2D but not in 3D. Is it possible to blend(BlendMode.ADD) Rectangles or Box-es(with small depth) to construct particle system 3D version in javafx8?
here is the code(using meshes but similar with Rectangles also doesn't work in 3D ) :
public class PS2 extends Application {
private PerspectiveCamera ps ;
public MeshView textMesh(){
float [] points={
-100f,-100f,0f,
100f,-100f,0f,
100f,100f,0f,
-100f,100f,0f
} ;
float [] textCord={
0f,0f,
1f,0f,
1f,1f,
0f,1f
} ;
int[] faces={
0,0,3,3,1,1,
0,0,1,1,3,3,
3,3,2,2,1,1,
3,3,1,1,2,2
} ;
TriangleMesh mesh=new TriangleMesh() ;
mesh.getPoints().addAll(points);
mesh.getTexCoords().addAll(textCord);
mesh.getFaces().addAll(faces);
MeshView kv=new MeshView() ;
kv.setMesh(mesh) ;
PhongMaterial pm=new PhongMaterial() ;
pm.setDiffuseMap(new Image("file:/c:/pdfs/prs.png"));
kv.setMaterial(pm);
return kv ;
}
public void particleSystem(Group g){
//ArrayList<MeshView> particles=new ArrayList<>() ;
for(int i=0;i<20;i++){
MeshView mv=textMesh() ;
double x= (new Random()).nextDouble()*100.0 ;
double y= (new Random()).nextDouble()*100.0 ;
double z= (new Random()).nextDouble()*100.0 ;
mv.setTranslateX(x);
mv.setTranslateY(y);
mv.setTranslateZ(z);
//particles.add(mv) ;
mv.setBlendMode(BlendMode.ADD);
g.getChildren().add(mv) ;
}
}
public void initCamera(Scene scene){
ps=new PerspectiveCamera(true) ;
ps.setNearClip(0.1);
ps.setFarClip(10000);
ps.setTranslateZ(-2100);
ps.setTranslateX(100);
ps.setTranslateY(100);
scene.setCamera(ps);
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Particle Systems");
Group root=new Group() ;
Scene s=new Scene(root,400,400,true) ;
s.setFill(Color.BLACK);
initCamera(s) ;
particleSystem(root);
primaryStage.setScene(s);
primaryStage.show() ;
}
public static void main(String[] args) {
launch(args) ;
}
}
Related
I am new to JavaFx and i am making a simple drawing program where i draw shapes. The problem i am having now is that i dont know how to make the circle appear on the screen when i click on the screen. So first I want to press a button that says "Circle" and then when i click on the canvas i want it to spawn. (I am switching between scenebuilder and intellij btw).
This is some of my program:
Classes:
public abstract class Shape {
double x;
double y;
double width;
double height;
public Color color = Color.WHITE;
public void creatingShapes(double x, double y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void setColor(Color color) {
this.color = color;
}
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;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Color getColor() {
return color;
}
public abstract void draw(GraphicsContext g);
}
public class Circle extends Shape {
#Override
public void draw(GraphicsContext g) {
g.setFill(color);
g.fillOval(200,200,200,200);
g.fillRect(getX(),getY(),getWidth(),getHeight());
g.setStroke(Color.BLACK);
g.strokeOval(getX(),getY(),getWidth(),getHeight());
====================================================
Controller class:
public class HelloController {
#FXML
private Button logoutButton;
#FXML
private BorderPane scenePane;
Stage stage;
#FXML
private ColorPicker myColorPicker;
#FXML
private ChoiceBox<String> myChoiceBox;
#FXML
private Button circle;
#FXML
private GraphicsContext g;
private final Shape[] shapes = new Shape[500];
Canvas canvas = new Canvas(310,333);
boolean drawShape = true;
int count = 0;
private final Color currentColor = Color.BLUE;
private final String[] menuAlternatives = {"Sparning", "Testing?", "Exit?"};
public void onCircleClicked() {
circle.setOnAction((event) -> addShape(new Circle()));
}
//skapa shapes
public void addShape(Shape shape) {
shape.setColor(currentColor);
shape.creatingShapes(10,10,150,100);
shapes[count] = shape;
count++;
paintCanvas();
}
public void changeColor(ActionEvent event) {
Color myColor = myColorPicker.getValue();
scenePane.setBackground(new Background(new BackgroundFill(myColor, null, null)));
}
public void initialize() {
g = canvas.getGraphicsContext2D();
}
public void paintCanvas() {
g.setFill(Color.WHITE);
g.fillRect(0,0,400,400);
Arrays.stream(shapes, 0, count).forEach(s -> s.draw(g));
}
Placing a circle on canvas with mouse event
From Doc
public void fillOval(double x,
double y,
double w,
double h)
Fills an oval using the current fill paint.
This method will be affected by any of the global common or fill attributes
as specified in the Rendering Attributes Table.
Parameters:
x - the X coordinate of the upper left bound of the oval.
y - the Y coordinate of the upper left bound of the oval.
w - the width at the center of the oval.
h - the height at the center of the oval.
As we can see x and y params from fillOval() will put the circle at the left upper corner of its bound . to spawn at its very center , we need to subtract half widht and half height to x and y coordinates given by mouseclick event.
this is a single class javafx app you can try
App.java
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage stage) {
Canvas canvas = new Canvas(640, 480);
GraphicsContext context = canvas.getGraphicsContext2D();
canvas.setOnMouseClicked(e -> {
double x = e.getX();
double y = e.getY();
context.setFill(Color.AQUAMARINE);
context.setStroke(Color.BLACK);
context.fillOval(x - 20, y - 20, 40, 40);
context.strokeOval(x - 20, y - 20, 40, 40);
});
var scene = new Scene(new Group(canvas), 640, 480);
stage.setScene(scene);
stage.setTitle("spawn with mouse click");
stage.show();
}
public static void main(String[] args) {
launch();
}
}
This is a c# script for unity that is supposed to (onClick) and (onRelease) store the X and Y position of the cursor as floats, assign those to an array of [2], calculate the magnitude between the two points...
And here's where I'm stuck
I need to save those values into a list or array that I can print ToString() for debugging, as well as make those individual coordinates still accessible to the program.
Ideally I want to store values formatted like this:
listOfSavedCoordinates
{
[0] {{X1 , Y1}, {X2 , Y2} , {Magnitude}}
}
And to be able to access them by referencing the index of the list, then the jagged array's indexes.
Here's my who script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickDrag : MonoBehaviour
{
public class Coordinate
{
public static float X { get => Input.mousePosition.x; }
public static float Y { get => Input.mousePosition.y; }
public static float[] XY1 { get; set; }
public static float[] XY2 { get; set; }
public static float XY3 { get; set; }
}
public class Action
{
public static float[] XY1 { get; set; }
public static float[] XY2 { get; set; }
public static float[] Magnitude { get; set; }
}
[HideInInspector] public float X1;
[HideInInspector] public float Y1;
[HideInInspector] public float X2;
[HideInInspector] public float Y2;
public static float Magnitude;
//The list I want to save my coordinates and magnitudes to
List<float[,]> listOfSavedCoordinates = new List<float[,]>();
public static float CalculateMagnitude(float X2, float X1, float Y2, float Y1)
{//calculates the distance between 2 X,Y points. Called in OnRelease()
float Xsqr = (X2 - X1) * (X2 - X1);
float Ysqr = (Y2 - Y1) * (Y2 - Y1);
float XYsqr = Xsqr + Ysqr;
float magnitude = Mathf.Sqrt(XYsqr);
return magnitude;
}
private void SaveCoordsAndMag(float X1, float Y1, float X2, float Y2, float M)
{//saves action coordinates and magnitude to a list. Called in OnRelease()
Action.XY1 = new float[2] { X1, Y1 };
Action.XY2 = new float[2] { X2, Y2 };
Action.Magnitude = new float[1] { M } ;
listOfSavedCoordinates.Add(new float[3, 1] { { Action.XY1 }, { Action.XY2 }, { Action.Magnitude } });
//STACKOVERFLOW: This is the method I want to use to save the elements to my list.
//the problem is that adding the arrays requires an array initializer even though the values are already arrays,
//so initializing them makes the array expect a float.
//Please help thank you
}
// Use this for initialization
void Start()
{
Debug.Log("Game Start!");
Debug.Log("Click and drag the mouse to create vectors");
Debug.Log("Press M to show previous vectors");
}
// Update is called once per frame
void Update()
{
//Inputs
bool onClick = Input.GetKeyDown(KeyCode.Mouse0);
bool onDrag = Input.GetKey(KeyCode.Mouse0);
bool onRelease = Input.GetKeyUp(KeyCode.Mouse0);
if (onClick == true)
{//Coordinates for the start point
X1 = Coordinate.X;
Y1 = Coordinate.Y;
Debug.Log("Action Start!");
Debug.Log(X1 + " , " + Y1);
}
if (onDrag == true)
{//Coordinates of the current mouse position
float X3 = Coordinate.X;
float Y3 = Coordinate.Y;
Debug.Log("Action Charging! " + X3 + " , " + Y3);
}
if (onRelease == true)
{//Coordinates of the final point
X2 = Coordinate.X;
Y2 = Coordinate.Y;
Debug.Log("Action Released!");
Debug.Log(X2 + " , " + Y2);
Magnitude = CalculateMagnitude(X2, X1, Y2, Y1);
Debug.Log("The magnitude is " + Magnitude);
SaveCoordsAndMag(X1, Y1, X2, Y2, Magnitude);
Debug.LogWarning(listOfSavedCoordinates.Count + " Actions Saved.");
}
if (Input.GetKeyDown(KeyCode.M) == true)
{
int xy1 = 0;
int xy2 = 1;
int mag = 2;
listOfSavedCoordinates.ToArray();
Debug.LogWarning(
listOfSavedCoordinates[xy1].ToString()
+ ','
+ listOfSavedCoordinates[xy2].ToString()
+ " ---> "
+ listOfSavedCoordinates[mag].ToString()
);
xy1 = xy1 + 3;
xy2 = xy1 + 1;
mag = xy2 + 1;
//STACKOVERFLOW: This is how I'd like to log my list's elements.
}
}
}
I figured out my issue. I needed to give my Action class's float array variables their index reference to get an actual value.
listOfSavedCoordinates.Add(new float[3,2] { { Action.XY1[0], Action.XY1[1] }, { Action.XY2[0], Action.XY2[1] }, { Action.Magnitude[0], listOfSavedCoordinates.Count } });
You should be doing something like this:
List<Coordinate> lstCoords = new List<Coordinate>();
// long handing this for understanding
Coordinate coord = new Coordinate();
// assign strongly typed vars in object to values here
coord.X1 = X1;
coord.X2 = X2;
coord.Y1 = Y1;
coord.Y2 = Y2;
// add the object to the list
lstCoords.Add(coord);
Then accessing each item would be something like this:
foreach (Coordinate coord in lstCoords)
{
console.writeline( coord.X1, coord.X2, coord.y1, coord.y2);
}
You can also search for a specific coordinate in the list, too.
But really, you want to use an list of objects vs trying to store data without strongly typed names.
I would suggest you to try this:
public class ClickDrag : MonoBehaviour
{
List<Coordinates> coordinatesList;
Vector2 startPos;
// Use this for initialization
void Start()
{
coordinatesList = new List<Coordinates>();
// Some other code
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
startPos = Input.mousePosition;
}
else if(Input.GetMouseButtonUp(0))
{
// Here create the new coordinates
Coordinates newCoordinates = new Coordinates(startPos, Input.mousePosition);
coordinatesList.Add(newCoordinates);
}
// Note here you don't need "== true", cause the method will already give you a boolean
if(Input.GetKeyDown(KeyCode.M))
{
DebugList();
}
}
private DebugList()
{
Debug.Log("listOfSavedCoordinates: ");
for(int i=0; i<coordinatesList.Count; i++)
Debug.Log("["+i+"] " + coordinatesList[i].PrintCoordinates());
}
}
public class Coordinates
{
private Vector2 startPos;
private Vector2 endPos;
private float magnitude;
public Coordinates(Vector2 startPos, Vector2 endPos)
{
this.startPos = startPos;
this.endPos = endPos;
magnitude = Vector2.Distance(startPos, endPos);
}
public PrintCoordinates()
{
return ("{" + startPos + "}, {" + endPos + "}, " + magnitude);
}
}
I am making a multiplayer MMO with unity and I am stuck on syncing up enemy spawning between clients. Basically the enemies spawn as intended, but only on the user that spawned them. Here is my code (Sorry it is a bit long, just wanted to include any information that could be relevant, as the is my first time with networking):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[System.Serializable]
public class EnemySpawn {
public GameObject prefab;
public int difficulty;
public int rarity;
[HideInInspector()]
public GameObject instance;
}
public class EnemySpawner : NetworkBehaviour {
public EnemySpawn[] enemys;
public int maxDiff = 8;
public int spawnDistMin = 15;
public int spawnDistMax = 35;
public int spawnLvlDist = 30;
private int diffOnScreen;
private EnemySpawn enemyToSpawn;
public List<EnemySpawn> enemysOnScreen = new List<EnemySpawn>();
void Start() {
StartCoroutine (Spawn());
}
void Update() {
List<EnemySpawn> newEnemysOnScreen = new List<EnemySpawn>();
foreach(EnemySpawn c in enemysOnScreen) {
if (c.instance == null) {
diffOnScreen -= c.difficulty;
} else {
newEnemysOnScreen.Add (c);
}
}
enemysOnScreen = newEnemysOnScreen;
}
//IMPORTANT PART!!! \/\/\/
[Command]
void CmdSpawn(Vector3 pos) {
GameObject spawning = Instantiate (enemyToSpawn.prefab, pos, Quaternion.identity);
NetworkServer.Spawn (spawning);
diffOnScreen += enemyToSpawn.difficulty;
enemysOnScreen.Insert (0,enemyToSpawn);
enemysOnScreen [0].instance = spawning;
spawning.GetComponent<MonsterMain>().lvl = Mathf.RoundToInt(spawning.transform.position.magnitude / spawnLvlDist);
}
IEnumerator Spawn() {
while (true) {
int n = 0;
while (n != 1) {
enemyToSpawn = enemys [Random.Range (0, enemys.Length)];
n = Random.Range (1, enemyToSpawn.rarity);
}
while (maxDiff - diffOnScreen <= enemyToSpawn.difficulty) {
yield return null;
}
yield return null;
Transform player = Player.localPlayer.transform;
Vector2 randomOffset = Random.insideUnitCircle.normalized * Random.Range (spawnDistMin, spawnDistMax);
CmdSpawn(player.position + new Vector3(randomOffset.x,randomOffset.y,0));
}
}
}
I am using Unity 2017.1.3.3p3, and I am building this to IOS. It is a 2d game and I am using unity's build in networking system. Again everything works except that the enemies only spawn on one screen. I am connecting one phone to the editor. Any help is appreciated. thank you!
With Unity3D I am trying to create a scene with an alpha texture as a silhouette, which upon looking up is added, then looking down removes.
Currently I have the exposure of an equirectangular image changing on look up, but my silhouette object says I have not assigned it to an instance:
As you can see from the console, it is eventualy recognised, but I cannot set the active state. This is the current state of my code being applied to the scene:
using UnityEngine;
using System.Collections;
public class switchScript : MonoBehaviour {
public Cardboard cb;
public Renderer leftEyeDay;
public Renderer rightEyeDay;
private GameObject[] dayObjects;
public GameObject nightObject;
void Start () {
MeshFilter filter = GetComponent(typeof (MeshFilter)) as MeshFilter;
if (filter != null) {
Mesh mesh = filter.mesh;
Vector3[] normals = mesh.normals;
for (int i=0;i<normals.Length;i++)
normals[i] = -normals[i];
mesh.normals = normals;
for (int m=0;m<mesh.subMeshCount;m++)
{
int[] triangles = mesh.GetTriangles(m);
for (int i=0;i<triangles.Length;i+=3)
{
int temp = triangles[i + 0];
triangles[i + 0] = triangles[i + 1];
triangles[i + 1] = temp;
}
mesh.SetTriangles(triangles, m);
}
}
}
// Update is called once per frame
void Update () {
float xAngle = cb.HeadPose.Orientation.eulerAngles.x;
if (isLookingUp (xAngle)) {
var exposureValue = getExposureValue (xAngle);
leftEyeDay.material.SetFloat ("_Exposure", exposureValue);
rightEyeDay.material.SetFloat ("_Exposure", exposureValue);
toggleNight ();
} else {
leftEyeDay.material.SetFloat ("_Exposure", 1F);
rightEyeDay.material.SetFloat ("_Exposure", 1F);
toggleNight ();
}
}
public bool isLookingUp (float xAngle) {
return xAngle > 270 && xAngle < 340;
}
public float getExposureValue (float xAngle) {
var _xAngle = Mathf.Clamp (xAngle, 320, 340);
return ScaleValue (320.0F, 340.0F, 0.3F, 1.0F, _xAngle);
}
public float ScaleValue (float from1, float to1, float from2, float to2, float v) {
return from2 + (v - from1) * (to2 - from2) / (to1 - from1);
}
void toggleDay() {
print (nightObject);
nightObject = GameObject.FindGameObjectWithTag ("Night");
nightObject.SetActive (false);
}
void toggleNight() {
print (nightObject);
nightObject = GameObject.FindGameObjectWithTag ("Night");
nightObject.SetActive (true);
}
}
GameObject.FindGameObjectWithTag ("Night") returns null when the whole object is set to !active. Just toggle the scripts on that object instead of the whole GO.
Ok, if anyone needs this, this is an easy way to create scene switch:
void Awake() {
silhouetteObject = GameObject.FindGameObjectWithTag ("Night");
silhouetteObject.GetComponent<Renderer>().enabled = false;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a 2D car game for my University project.
I have developed it up to the point that user's car can move and traffic cars come from above. But I have no clue about how to destroy the user's car when it collied with a traffic car. Can anyone tell how to detect collision and after that how to destroy it.
public class MainActivity extends BaseGameActivity{
Scene scene; // declare a scene object
protected static final float CAMERA_WIDTH = 800; // define camera width
protected static final float CAMERA_HEIGHT = 520; //define camera height
/*----- background -----------*/
BitmapTextureAtlas backbitmapTextureAtlas; // declare a bitmap texture
ITextureRegion backiTextureRegion; // declare a i texture region to hold image
Sprite backsPlayer; // sprite to display the image
PhysicsWorld backpWorld;
SensorManager backsensor;
Vector2 backvec;
ITexture backparallax_background;
protected VertexBufferObjectManager backvbom;
org.andengine.engine.camera.Camera camera;
/*----- /background -----------*/
/*----user's car---------*/
BitmapTextureAtlas bitmapTextureAtlas;
ITextureRegion iTextureRegion;
Vector2 vec;
PhysicsWorld pWorld;
SensorManager sensor;
Sprite sPlayer;
/*----/user's car---------*/
/*------ traffic cars----------*/
BitmapTextureAtlas bitmapTextureAtlasTraffic1;
ITextureRegion iTextureRegionTraffic1;
Sprite sPlayerTraffic1;
BitmapTextureAtlas bitmapTextureAtlasTraffic2;
ITextureRegion iTextureRegionTraffic2;
Sprite sPlayerTraffic2;
BitmapTextureAtlas bitmapTextureAtlasTraffic3;
ITextureRegion iTextureRegionTraffic3;
Sprite sPlayerTraffic3;
BitmapTextureAtlas bitmapTextureAtlasTraffic4;
ITextureRegion iTextureRegionTraffic4;
Sprite sPlayerTraffic4;
MoveXModifier mod1;
MoveXModifier mod2;
MoveXModifier mod3;
MoveXModifier mod4;
/*------ /traffic cars----------*/
#Override
public EngineOptions onCreateEngineOptions() {
// TODO Auto-generated method stub
camera = new org.andengine.engine.camera.Camera(0,0,CAMERA_WIDTH,CAMERA_HEIGHT); // create camera
EngineOptions options= new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH,CAMERA_HEIGHT), camera); //create engine options
return options;
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws Exception {
// TODO Auto-generated method stub
/* ---------------parallax back code------------------*/
backparallax_background = new AssetBitmapTexture(this.getTextureManager(), this.getAssets(), "gfx/back2.png");
backiTextureRegion = TextureRegionFactory.extractFromTexture(this.backparallax_background);
this.backparallax_background.load();
/* ---------------/parallax back code------------------*/
loadGfx(); // load user's car
loadTraffic();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
/*--------load traffic cars------------*/
private void loadTraffic() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // give the path of image folder
bitmapTextureAtlasTraffic1 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic1 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic1, this, "traffic1.png", 0,0);
bitmapTextureAtlasTraffic1.load();
//----- traffic 2--------------
bitmapTextureAtlasTraffic2 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic2 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic2, this, "traffic2.png", 0,0);
bitmapTextureAtlasTraffic2.load();
//----- traffic 3--------------
bitmapTextureAtlasTraffic3 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic3 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic3, this, "traffic3.png", 0,0);
bitmapTextureAtlasTraffic3.load();
//----- traffic 4--------------
bitmapTextureAtlasTraffic4 = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegionTraffic4 = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlasTraffic4, this, "traffic4.png", 0,0);
bitmapTextureAtlasTraffic4.load();
}
/*--------load user's car------------*/
private void loadGfx() {
// TODO Auto-generated method stub
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); // give the path of image folder
bitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 256, 256);// create a bit map to hold the picture and give size according to the image
iTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(bitmapTextureAtlas, this, "usercar.png", 0,0);
bitmapTextureAtlas.load();
}
/*--------load user's car------------*/
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws Exception {
// TODO Auto-generated method stub
scene = new Scene(); // create the object of scene
/*------ parallax background---------*/
final AutoParallaxBackground auto_background = new AutoParallaxBackground(0, 0, 0, 200);
final Sprite background_sprite = new Sprite(0,0, this.backiTextureRegion,backvbom);
auto_background.attachParallaxEntity(new ParallaxEntity(1.7f,background_sprite));
scene.setBackground(auto_background);
pOnCreateSceneCallback.onCreateSceneFinished(scene);
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {
// TODO Auto-generated method stub
// set traffic car1
sPlayerTraffic1 = new Sprite(10,350,iTextureRegionTraffic1,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic2 = new Sprite(300,280,iTextureRegionTraffic2,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic3 = new Sprite(400,190,iTextureRegionTraffic3,this.mEngine.getVertexBufferObjectManager());
sPlayerTraffic4 = new Sprite(50,70,iTextureRegionTraffic4,this.mEngine.getVertexBufferObjectManager());
mod1=new MoveXModifier(5,-600,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(370-350)+350;// set y randomly
int speed = r.nextInt(3-2)+3; // set speed randomly
sPlayerTraffic1.setY(y); // set y
int x = r.nextInt(800-500)+200; // set x randomly
x = -x;
mod1.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic1 car
mod2=new MoveXModifier(4,200,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(300-285)+285; // set y randomly
int speed = r.nextInt(5-3)+3; // set speed randomly
sPlayerTraffic2.setY(y); // set y
int x = r.nextInt(600-200)+200; // set x randomly
x = -x;
mod2.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic2 car
mod3=new MoveXModifier(3,-600,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(190-150)+150;
int speed = r.nextInt(3-2)+2;
if(speed == 2){
y = 150;
}
sPlayerTraffic3.setY(y);
int x = r.nextInt(2000-800)+800;
x = -x;
mod3.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic3 car
mod4=new MoveXModifier(3,50,800){
#Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
Random r = new Random();
int y = r.nextInt(100-70)+70;
int speed = r.nextInt(3-2)+2;
sPlayerTraffic4.setY(y);
int x = r.nextInt(600-200)+200;
x = -x;
mod4.reset(speed, x, 800);
super.onModifierFinished(pItem);
}
};// moving down the traffic4 car
sPlayerTraffic1.registerEntityModifier(mod1);
sPlayerTraffic2.registerEntityModifier(mod2);
sPlayerTraffic3.registerEntityModifier(mod3);
sPlayerTraffic4.registerEntityModifier(mod4);
//now set the x,y coordination of the image to display the right position we want
sPlayer = new Sprite(500,350,iTextureRegion,this.mEngine.getVertexBufferObjectManager()){ // user's car x,y
// touch event for user's car
#Override
public boolean onAreaTouched(org.andengine.input.touch.TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY)
{
this.setPosition(500 , pSceneTouchEvent.getY());
//website code
this.setPosition(pSceneTouchEvent.getX(),
this.getY());
//Detects if player is outside of bounds
final float width = this.getWidth();
final float height = this.getHeight();
float x = pSceneTouchEvent.getX() - width / 2 ;
float y = pSceneTouchEvent.getY() - height / 2;
if (x < 0)
x = 0;
if (y < 65) // right side of the road
y = 65;
if (x > (CAMERA_WIDTH - width))
x = CAMERA_WIDTH - width;
if (y > (CAMERA_HEIGHT - height-70)) // left side of the road
y = (CAMERA_HEIGHT - height-70);
this.setPosition(500, y);
return true;
}
};
//touch ----------------------------------------------------------
scene.registerTouchArea(sPlayer);
//-----------------------------------------------------------------
this.scene.attachChild(sPlayer);
this.scene.attachChild(sPlayerTraffic1);
this.scene.attachChild(sPlayerTraffic2);
this.scene.attachChild(sPlayerTraffic3);
this.scene.attachChild(sPlayerTraffic4);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
}
private ContactListener createContactListener()
{
ContactListener contactListener = new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
final Fixture x1 = contact.getFixtureA();
final Fixture x2 = contact.getFixtureB();
if(x1==PlayerBody && x2==EnemyBody){
DestroyMethod();
}
}
};
return contactListener;
}
YourPhysicsWorld.setContactListener(createContactListener());
private void DestroyMethod(){
YourPhysicsWorld.destroyBody(EnemyBody);
}