Need help on Android car game [closed] - andengine

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);
}

Related

Unity game - generate circuit with line drawing

I'm not a very beginer in unity, but not so far ;).
Today, I want to make a game which is a mix pool pinball.
The game physic is quite ok for me, but my big challenge is :
what i want to do
Allow the player to draw his own circuit and then place the different item : bumper, sticky wall ...
I make it in 3D, but with the camera position, it will be like 2D.
First of all, I don't know how to make curvy gameobject. I know about bezier curve generator, but not how generate shape with.
Ideally, it would be great if I could : draw a line (with the mouse or finder position) like a line renderer component and then unity extrude in one direction the field circuit. And that' it I have my circuit.
The second challenge will be to place (whit mouse or finger) the different component : bumper, players... with some rules : A sticky wall have to be on a simple wall from the circuit, not in the middle, you have to alway keep some space for the balls etc...
Then we create a game circuit, then we could play :):)
I work with the last unity version.
Obviously, I don't expect a full solution:rolleyes:, but according to you, is it possible ? And which way, which technic I should learn to do that? Which could be the big issu ? ... any remark advice is good to take.
I already begin to look at https://unity3d.com/fr/learn/tutori...ation-tutorial/creating-meshes?playlist=17153, I d'ont know if it's completly too much or not ?
Many thanks for your help,
Axel
Here my solution
using System.IO;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.Networking;
public class scri : MonoBehaviour
{
// For saving the mesh------------------------
public KeyCode saveKey = KeyCode.F12;
public string saveName = "SavedMesh";
// Concerning mesher--------------------------
public GameObject mesher; //require
public List<Vector3> vertices;
public List<int> triangles;
public Vector3 point0;
public Vector3 point1;
public Vector3 point2;
public Vector3 point3;
public int loop;
public float size;
public Mesh meshFilterMesh;
public Mesh meshColliderMesh;
// Sprite work
public Color[] pixels;
public Texture2D newTexture;
public Texture2D oldTexture; //require
private Sprite mySprite;
private SpriteRenderer spriteRenderer;
public int pathCount;
public GameObject displayerComponent; //require
public PolygonCollider2D polygonColliderAdded; //require
void Start()
{
// Mesher
vertices = new List<Vector3> ();
triangles = new List<int> ();
meshFilterMesh= mesher.GetComponent<MeshFilter>().mesh;
meshColliderMesh= mesher.GetComponent<MeshCollider>().sharedMesh;
size = 10; // lenght of the mesh in Z direction
loop=0;
// Sprite
pixels = oldTexture.GetPixels();
newTexture =new Texture2D(oldTexture.width,oldTexture.height,TextureFormat.ARGB32, false);
spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
ConvertSpriteAndCreateCollider (pixels);
BrowseColliderToCreateMesh (polygonColliderAdded);
}
void Update()
{
// Save if F12 press
if (Input.GetKeyDown(saveKey)){SaveAsset();}
}
public void ConvertSpriteAndCreateCollider (Color[] pixels) {
for (int i = 0 ; i < pixels.Length ; i++ )
{
// delete all black pixel (black is the circuit, white is the walls)
if ((pixels[i].r==0 && pixels[i].g==0 && pixels[i].b==0 && pixels[i].a==1)) {
pixels[i] = Color.clear;
}
}
// Set a new texture with this pixel list
newTexture.SetPixels(pixels);
newTexture.Apply();
// Create a sprite from this texture
mySprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(10.0f,10.0f), 10.0f, 0, SpriteMeshType.Tight,new Vector4(0,0,0,0),false);
// Add it to our displayerComponent
displayerComponent.GetComponent<SpriteRenderer>().sprite=mySprite;
// Add the polygon collider to our displayer Component and get his path count
polygonColliderAdded = displayerComponent.AddComponent<PolygonCollider2D>();
}
// Method to browse the collider and launch makemesh
public void BrowseColliderToCreateMesh (PolygonCollider2D polygonColliderAdded){
//browse all path from collider
pathCount=polygonColliderAdded.pathCount;
for (int i = 0; i < pathCount; i++)
{
Vector2[] path = polygonColliderAdded.GetPath(i);
// browse all path point
for (int j = 1; j < path.Length; j++)
{
if (j != (path.Length - 1)) // if we aren't at the last point
{
point0 = new Vector3(path[j-1].x ,path[j-1].y ,0);
point1 = new Vector3(path[j-1].x ,path[j-1].y ,size);
point2 = new Vector3(path[j].x ,path[j].y ,size);
point3 = new Vector3(path[j].x ,path[j].y ,0);
MakeMesh(point0,point1,point2,point3);
}
else if(j == (path.Length - 1))// if we are at the last point, we need to close the loop with the first point
{
point0 = new Vector3(path[j-1].x ,path[j-1].y ,0);
point1 = new Vector3(path[j-1].x ,path[j-1].y ,size);
point2 = new Vector3(path[j].x ,path[j].y ,size);
point3 = new Vector3(path[j].x ,path[j].y ,0);
MakeMesh(point0,point1,point2,point3);
point0 = new Vector3(path[j].x ,path[j].y ,0);
point1 = new Vector3(path[j].x ,path[j].y ,size);
point2 = new Vector3(path[0].x ,path[0].y ,size); // First point
point3 = new Vector3(path[0].x ,path[0].y ,0); // First point
MakeMesh(point0,point1,point2,point3);
}
}
}
}
//Method to generate 2 triangles mesh from the 4 points 0 1 2 3 and add it to the collider
public void MakeMesh (Vector3 point0,Vector3 point1,Vector3 point2, Vector3 point3){
// Vertice add
vertices.Add(point0);
vertices.Add(point1);
vertices.Add(point2);
vertices.Add(point3);
//Triangle order
triangles.Add(0+loop*4);
triangles.Add(2+loop*4);
triangles.Add(1+loop*4);
triangles.Add(0+loop*4);
triangles.Add(3+loop*4);
triangles.Add(2+loop*4);
loop = loop + 1;
// create mesh
meshFilterMesh.vertices=vertices.ToArray();
meshFilterMesh.triangles=triangles.ToArray();
// add this mesh to the MeshCollider
mesher.GetComponent<MeshCollider>().sharedMesh=meshFilterMesh;
}
// Save if F12 press
public void SaveAsset()
{
var mf = mesher.GetComponent<MeshFilter>();
if (mf)
{
var savePath = "Assets/" + saveName + ".asset";
Debug.Log("Saved Mesh to:" + savePath);
AssetDatabase.CreateAsset(mf.mesh, savePath);
}
}
}

Painting sprite in unity

Problem :
I want to make prototype for cleaning windows (I mean cleaning dirty windows) in unity.
I was searching about this subject and finding that I can change pixel by Texture2D.SetPixel().
I try to do it by this method, First I enabled read/write of texture and try this method but nothing happened on my sprite.
So I want to ask it if it's possible to change alpha of the sprite that is clicked by mouse or touched to show the below sprite of original one !?
My Code :
private RaycastHit2D hitInfo;
private SpriteRenderer spriteRendererComponent;
private Color zeroAlpha;
// Use this for initialization
void Start ()
{
spriteRendererComponent = transform.GetComponent<SpriteRenderer>();
zeroAlpha = Color.blue;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
MouseClick();
}
}
public void MouseClick()
{
Vector2 mousePosition = Vector2.zero;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hitInfo = Physics2D.Raycast(mousePosition, Vector2.zero);
if (hitInfo)
{
spriteRendererComponent.sprite.texture.SetPixel((int)hitInfo.point.x, (int)hitInfo.point.y, zeroAlpha);
spriteRendererComponent.sprite.texture.Apply();
}
}
Answer :
You can use this thread for Optimizing of changing pixels of sprite
I've found answer about changing pixels of sprite (Painting)
public float radius;
public Color InitialColor;
private RaycastHit2D hitInfo;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (CustomInput.ControlStay())
{
hitInfo = CustomInput.ClickednTouched().hitInfo;
if (hitInfo)
{
UpdateTexture();
}
}
}
public Texture2D CopyTexture2D(Texture2D copiedTexture2D)
{
float differenceX;
float differenceY;
//Create a new Texture2D, which will be the copy
Texture2D texture = new Texture2D(copiedTexture2D.width, copiedTexture2D.height);
//Choose your filtermode and wrapmode
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
//Center of hit point circle
int m1 = (int)((hitInfo.point.x + 2.5f) / 5 * copiedTexture2D.width);
int m2 = (int)((hitInfo.point.y + 2.5f) / 5 * copiedTexture2D.height);
for (int x = 0; x < texture.width; x++)
{
for (int y = 0; y < texture.height; y++)
{
differenceX = x - m1;
differenceY = y - m2;
//INSERT YOUR LOGIC HERE
if (differenceX * differenceX + differenceY * differenceY <= radius * radius)
{
//This line of code and if statement, turn all texture pixels within radius to zero alpha
texture.SetPixel(x, y, InitialColor);
}
else
{
//This line of code is REQUIRED. Do NOT delete it. This is what copies the image as it was, without any change
texture.SetPixel(x, y, copiedTexture2D.GetPixel(x, y));
}
}
}
//This finalizes it. If you want to edit it still, do it before you finish with Apply(). Do NOT expect to edit the image after you have applied.
texture.Apply();
return texture;
}
public void UpdateTexture()
{
SpriteRenderer mySpriteRenderer = gameObject.GetComponent<SpriteRenderer>();
Texture2D newTexture2D = CopyTexture2D(mySpriteRenderer.sprite.texture);
//Get the name of the old sprite
string tempName = mySpriteRenderer.sprite.name;
//Create a new sprite
mySpriteRenderer.sprite = Sprite.Create(newTexture2D, mySpriteRenderer.sprite.rect, new Vector2(0.5f, 0.5f));
//Name the sprite, the old name
mySpriteRenderer.sprite.name = tempName;
//Update the material
//If you have multiple sprites, you will want to do this in a loop
//mySpriteRenderer.material.mainTexture = newTexture2D;
//mySpriteRenderer.material.shader = Shader.Find("Unlit/Transparent");
}
Another problem :
Finding pixel on sprite :
In Unity3d we have RaycastHit.textureCoord but it doesn't exist anymore in 2D. I was searching about this problem, a lot but I didn't find anything useful.
So I want to know the solution for this problem and I'm wondering why method like textureCoord in 3D doesn't exist in 2D.
Answer :
I've found answer again as you see in the previous code for finding pixel on sprite.
Thread : Finding pixel on sprite in Unity
Check this out!
I have fixed your script. Works on different texture sizes. Different texture places and camera size. Require box collider 2d.
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public float radius;
public Color InitialColor;
private RaycastHit2D hitInfo;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hitInfo)
{
UpdateTexture();
}
}
if (Input.GetMouseButtonUp(0))
{
Resources.UnloadUnusedAssets();
}
}
public Texture2D CopyTexture2D(Texture2D copiedTexture2D)
{
float differenceX;
float differenceY;
//Create a new Texture2D, which will be the copy
Texture2D texture = new Texture2D(copiedTexture2D.width, copiedTexture2D.height);
//Choose your filtermode and wrapmode
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
//Center of hit point circle
int m1 = (int)((hitInfo.point.x - hitInfo.collider.bounds.min.x) * (copiedTexture2D.width / hitInfo.collider.bounds.size.x));
int m2 = (int)((hitInfo.point.y - hitInfo.collider.bounds.min.y) * (copiedTexture2D.height / hitInfo.collider.bounds.size.y));
//Vector2 extremeScreenPoint = Camera.main.ScreenToWorldPoint(new Vector2(0, 0));
//Debug.Log("extremeScreenPoint= " + extremeScreenPoint.x
// + " hitInfo.point.x =" + hitInfo.point.x
// //+ " mousePosition =" + Camera.main.ScreenToWorldPoint(Input.mousePosition).x
// + " bounds.min =" + hitInfo.collider.bounds.min .x
// + " bounds.max =" + hitInfo.collider.bounds.max .x
// + " size =" + hitInfo.collider.bounds.size.x
// + " hit =" + (hitInfo.point.x - hitInfo.collider.bounds.min.x)
// + " pixels =" + (hitInfo.point.x - hitInfo.collider.bounds.min.x) * (copiedTexture2D.width / hitInfo.collider.bounds.size.x)
// );
for (int x = 0; x < texture.width; x++)
{
for (int y = 0; y < texture.height; y++)
{
differenceX = x - m1;
differenceY = y - m2;
//INSERT YOUR LOGIC HERE
if (differenceX * differenceX + differenceY * differenceY <= radius * radius)
{
//This line of code and if statement, turn all texture pixels within radius to zero alpha
texture.SetPixel(x, y, InitialColor);
}
else
{
//This line of code is REQUIRED. Do NOT delete it. This is what copies the image as it was, without any change
texture.SetPixel(x, y, copiedTexture2D.GetPixel(x, y));
}
}
}
//This finalizes it. If you want to edit it still, do it before you finish with Apply(). Do NOT expect to edit the image after you have applied.
texture.Apply();
//DestroyImmediate(copiedTexture2D, true);
return texture;
}
public void UpdateTexture()
{
SpriteRenderer mySpriteRenderer = gameObject.GetComponent<SpriteRenderer>();
Texture2D newTexture2D = CopyTexture2D(mySpriteRenderer.sprite.texture);
//Get the name of the old sprite
string tempName = mySpriteRenderer.sprite.name;
//Create a new sprite
mySpriteRenderer.sprite = Sprite.Create(newTexture2D, mySpriteRenderer.sprite.rect, new Vector2(0.5f, 0.5f));
//Name the sprite, the old name
mySpriteRenderer.sprite.name = tempName;
//Update the material
//If you have multiple sprites, you will want to do this in a loop
//mySpriteRenderer.material.mainTexture = newTexture2D;
//mySpriteRenderer.material.shader = Shader.Find("Unlit/Transparent");
}
}
I worked with Writing and Reading a Texture once (for a scratching card).
You have to consider that when you change the Pixels of the Sprite, you are changing the pixels for the entire texture. So let's say that i change the pixel 1x1, most likely it will not change the pixel 1x1 in my sprite if i have a bunch of sprites in the same texture. So you have to consider the offsets of the sprite and reposition the pixel that you want to change.
Try to do something like this:
public void MouseClick()
{
Vector2 offset = new Vector2(XXX, YYY);
Vector2 mousePosition = Vector2.zero;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hitInfo = Physics2D.Raycast(mousePosition, Vector2.zero);
if (hitInfo)
{
spriteRendererComponent.sprite.texture.SetPixel((int)hitInfo.point.x + offset.x, (int)hitInfo.point.y + offset.y, zeroAlpha);
spriteRendererComponent.sprite.texture.Apply();
}
}

LibGDX: How to keep displaying actor after drag (drag off)

I have implemented drag and drop, but the problem is after user releases the drag. The dragged actor is dissapear from the screen. How to move actor to its new location or return to its location if it is dropped not in its proper locations?
Thanks for your answers.
Regards,
Alfa
'
final DragAndDrop dragAndDrop = new DragAndDrop();
final Box sourceBox = boxList.get(0);
final Box targetBox = boxHolderList.get(0);
Source source = new Source(sourceBox) {
#Override
public void dragStop(InputEvent event, float x, float y,
int pointer, Payload payload, Target target) {
Box sourceBox = (Box) payload.getDragActor();
if (target == null){
sourceBox.setPosition(sourceBox.getX(), sourceBox.getY());
}
else{
Box targetBox = (Box) target.getActor();
sourceBox.setPosition(targetBox.getX(), targetBox.getY());
}
}
#Override
public Payload dragStart(InputEvent event, float x, float y, int pointer) {
dragAndDrop.setDragActorPosition(-1*sourceBox.getWidth()/2, 1*sourceBox.getHeight()/2);
Payload payload = new Payload();
payload.setDragActor(sourceBox);
Label validLabel = new Label("Valid!", skin);
validLabel.setColor(0, 1, 0, 1);
payload.setValidDragActor(validLabel);
Label invalidLabel = new Label("Invalid!", skin);
invalidLabel.setColor(1, 0, 0, 1);
payload.setInvalidDragActor(invalidLabel);
return payload;
}
};
this drag and drop method is quite mesh, you may try this
yourActor.addListener(new DragListener(){
public void touchDragged(InputEvent event, float x, float y, int pointer) {
yourActor.moveBy(x-yourActor.getWidth()/2,y-yourActor.getHeight()/2);
}});

Move a ball with the accelerometer andengine

I had written a code to move a ball with the help of accelerometer andengine, but i get force close.
My problem is the use of PhysicsWorld.
My library is:
andengine.jar
andenginephysicsbox2dextension.jar
my code is:
public class SnakeGameActivity extends BaseGameActivity implements IAccelerometerListener
{
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
private float mGravityX;
private float mGravityY;
private Sprite splash ;
private final Vector2 mTempVector = new Vector2();
protected PhysicsWorld mPhysicsWorld;
private Camera mCamera;
private Texture mTexture;
private TextureRegion mSplashTextureRegion;
#Override
public Engine onLoadEngine() {
// TODO Auto-generated method stub
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
#Override
public void onLoadResources() {
// TODO Auto-generated method stub
this.mTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
this.enableAccelerometerSensor(this);
this.mSplashTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "ball_enemy.png", 0, 0);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mEngine.getTextureManager().loadTexture(this.mTexture);
}
#Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
Scene scene = new Scene(1);
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
final int centerX = (CAMERA_WIDTH - this.mSplashTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mSplashTextureRegion.getHeight()) / 2;
splash = new Sprite(centerX, centerY, this.mSplashTextureRegion);
scene.getLastChild().attachChild(splash);
scene.registerUpdateHandler(this.mPhysicsWorld);
return scene;
}
#Override
public void onLoadComplete() {
// TODO Auto-generated method stub
}
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY());
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
}
my log error:
02-25 21:08:22.334: E/ActivityManager(69): Start proc com.android.deskclock for
broadcast com.android.deskclock/.AlarmInitReceiver: pid=255 uid=10019 gids={}
CPU usage from 16953ms to 19171ms later:
Thank you very much for your help

Andengine Live wallpaper : Loosing textures on low end device

I am developing a live wallpaper using Andengine GLES2 Anchor centre branch ,based on the Development Cookbook.Wallpaper works fine on mid range to high end devices but shows problem on low end devices.I have tested it on Samsung galaxy ace , Micromax Funbook tablet and the issue generator Samsung galaxy Y. Issue found only on Samsung galaxy Y the only low end device I have.
Issue
I got loosing textures of all sprites when unlocking screens sometimes,or when returning to homepage some times,Error is not generated in a predictable manner, some times it doesn't cause any issue at all, But when it occurs to make my work even in my preview mode I have to force close the application and start the app again.
These are the details of my live wallpaper,
Wallpaper have A background sprite,A main image sprite ,two BatchedSpriteParticleSystem with some initializers and modifiers
I have a sepretae folder in asset for lower end device (320*480) where I keep small images and load all images to a single texture atlas in that case other wise I am using two texture atlas one for background image,and one for my main image and the two particle images.I am using a resource manager calss as per the andengine cookbook to load textures
Please help me to sort out the issue,I dont know where iam going wrong on this
here is my code ...
LiveWallpaperExtensionService given below
LiveWallpaperExtensionService
#TargetApi(13)
public class LiveWallpaperExtensionService extends BaseLiveWallpaperService {
public Sprite bg_Sprite;
public Sprite main_image_sprite;
public SpriteBackground background;
public BatchedSpriteParticleSystem beamParticleSystem;
public BatchedSpriteParticleSystem starParticleSystem;
private Camera mCamera;
private Scene mScene;
#Override
public org.andengine.engine.Engine onCreateEngine(
final EngineOptions pEngineOptions) {
return new FixedStepEngine(pEngineOptions, 50);
}
public EngineOptions onCreateEngineOptions() {
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
Utils.setGlobalWidthandHeight(Utils.getDisplaySize(display));
mCamera = new Camera(0, 0, Global.Width, Global.Height);
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.PORTRAIT_SENSOR, new FillResolutionPolicy(),
mCamera);
engineOptions.getRenderOptions().setDithering(true);
return engineOptions;
}
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
System.out.println("On create resourses");
ResourceManager.getInstance().loadBlueTextures(mEngine, this);
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
System.out.println("On create scene");
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
public void onPopulateScene(Scene arg0,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
System.out.println("on populate ");
final float positionX = Global.Width * 0.5f;
final float positionY = Global.Height * 0.5f;
bg_Sprite = new Sprite(positionX, positionY,
ResourceManager.getInstance().mBackgroundTextureRegion,
this.getVertexBufferObjectManager());
main_image_sprite = new Sprite(positionX, positionY,
ResourceManager.getInstance().mJesusTextureRegion,
this.getVertexBufferObjectManager());
/*
* Define the center point of the particle system spawn location
*/
final int bparticleSpawnCenterX = (int) (Global.Width * 0.5f);
final int bparticleSpawnCenterY = (int) ((Global.Height * 0.5f) + ((Global.Height * 0.5f)) * 0.5f) - 25;
/* Define the radius of the circle for the particle emitter */
final float particleEmitterRadius = 50;
/* Create the particle emitter */
CircleOutlineParticleEmitter bparticleEmitter = new CircleOutlineParticleEmitter(
bparticleSpawnCenterX, bparticleSpawnCenterY,
particleEmitterRadius);
beamParticleSystem = new BatchedSpriteParticleSystem(bparticleEmitter,
10, 15, 50, ResourceManager.getInstance().mBeamTextureRegion,
mEngine.getVertexBufferObjectManager());
beamParticleSystem
.addParticleInitializer(new ExpireParticleInitializer<UncoloredSprite>(
3));
beamParticleSystem
.addParticleInitializer(new AccelerationParticleInitializer<UncoloredSprite>(
-150, 150, -150, 150));
RectangleParticleEmitter particleEmitter = new RectangleParticleEmitter(
((int) (Global.Width * 0.5f)), ((int) (Global.Height * 0.5f)),
Global.Width, Global.Height);
// Create a batched particle system for efficiency
starParticleSystem = new BatchedSpriteParticleSystem(particleEmitter,
1, 2, 20, ResourceManager.getInstance().mStarTextureRegion,
mEngine.getVertexBufferObjectManager());
/* Add an acceleration initializer to the particle system */
starParticleSystem
.addParticleInitializer(new ExpireParticleInitializer<UncoloredSprite>(
10));
starParticleSystem
.addParticleInitializer(new RotationParticleInitializer<UncoloredSprite>(
0, 160));
/* Define min/max values for the particle's scale */
starParticleSystem
.addParticleInitializer(new ScaleParticleInitializer<UncoloredSprite>(
0.3f, 1.5f));
/* Define the alpha modifier's properties */
starParticleSystem
.addParticleModifier(new AlphaParticleModifier<UncoloredSprite>(
0, 2, 0, 1));
/* Define the rotation modifier's properties */
starParticleSystem
.addParticleModifier(new RotationParticleModifier<UncoloredSprite>(
1, 9, 0, 180));
// Add alpha ('fade out') modifier
starParticleSystem
.addParticleModifier(new AlphaParticleModifier<UncoloredSprite>(
8, 10, 1, 0));
/*
* Create the SpriteBackground object, specifying the color values &
* Sprite object to display
*/
final float red = 0.7f;
final float green = 0.78f;
final float blue = 0.85f;
final float alpha = 1;
background = new SpriteBackground(red, green, blue, bg_Sprite);
mScene.setBackground(background);
mScene.setBackgroundEnabled(true);
// Attach our particle system to the scene
mScene.attachChild(starParticleSystem);
mScene.attachChild(beamParticleSystem);
mScene.attachChild(main_image_sprite);
bg_Sprite.setIgnoreUpdate(true);
main_image_sprite.setIgnoreUpdate(true);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
#Override
protected synchronized void onPause() {
System.out.println("On paused");
super.onPause();
if (starParticleSystem != null) {
starParticleSystem.setParticlesSpawnEnabled(false);
}
if (beamParticleSystem != null) {
beamParticleSystem.setParticlesSpawnEnabled(false);
}
}
#Override
protected synchronized void onResume() {
System.out.println("On resume");
super.onResume();
if (starParticleSystem != null) {
starParticleSystem.setParticlesSpawnEnabled(true);
}
if (beamParticleSystem != null) {
beamParticleSystem.setParticlesSpawnEnabled(true);
}
}
}
}
Please help me to sort out this issue ,I welcomes all ideas Suggestions, Any thing any thoughts of you to solve this issue ....
I've noticed that Galaxy Y has lots of issues, been getting lots of crash reports for a game of mine till I blocked them from downloading it and all reports stopped [it was the only device with issues]
I suggest you do the same
edit:
if you want to chose which devices to support, you can use this example
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
android:anyDensity="true" />
modify that as you see fit