Andengine Live wallpaper : Loosing textures on low end device - andengine

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

Related

What I Have Learned About Unity ScrollRect / ScrollView Optimization / Performance

ScrollView performance is a real drag (get it?), especially on mobile platforms. I frequently found myself getting less that 15 fps which left the user experience feeling jolting and underwhelming. After a lot of research and testing I have compiled a checklist to drastically improve performance. I now get at least 30 fps, with the majority of the CPU time allocated to WaitForTargetFPS.
I hope this helps anyone who is also having trouble in this area. Optimization solutions are hard to come by. Feel free to use and modify any of my code here.
ONE:
.GetComponent<>() calls are inefficient, especially outside the editor. Avoid using these in any kind of Update() method.
TWO:
OnValueChanged() is called every frame that the ScrollView is being dragged. It is therefore in a sense equivalent to Update() so you should avoid using .GetComponent<>() calls in this method.
THREE:
Whenever any element on a Canvas is changed the entire Canvas must rebuild its batches. This operation can be very expensive. It is therefore recommended to split your UI elements across at least two Canvases, one for elements that are changed rarely or never and one elements that change often.
Whenever a ScrollView scrolls the entire Canvas it is on is dirtied. It is therefore recommended that you have each ScrollView on a separate Canvas.
Unity Canvas Rebuilds Explanation: https://unity3d.com/learn/tutorials/topics/best-practices/fill-rate-canvases-and-input?playlist=30089
FOUR:
EventSystem.Update() handles the input detection in a scene, using raycasts to filter through the hierarchy in order to find a component to accept this input. Therefore these calculations are only done when interacting with the scene, like when a ScrollView is being scrolled. Removing unnecessary RaycastTarget properties from graphics and text will improve this processing time. It mightn't make a big difference, but if you're not careful enough objects can make the input handling time really add up.
FIVE:
With any kind of mask component, even a RectMask2D, all objects in a ScrollView are batched and rendered. If you have a lot of elements in your ScrollView, it is recommended that you utilize some kind of pooling solution. There are many of these available on the app store.
Unity Pooling Explanation: https://unity3d.com/learn/tutorials/topics/best-practices/optimizing-ui-controls
If, however, your project is incompatible with this, needing persistent elements, I would recommend that you hide your off screen objects to reduce performance overhead. Transform.SetParent() and GameObject.SetActive() are both resource intensive methods, instead attach a CanvasGroup component to each element and adjust the alpha value to achieve the same effect.
Here is a static script to detect if an object is visible or not and to set the alpha accordingly:
using UnityEngine;
using UnityEngine.UI;
public class ScrollHider : MonoBehaviour {
static public float contentTop;
static public float contentBottom;
static public bool HideObject(GameObject givenObject, CanvasGroup canvasGroup, float givenPosition, float givenHeight) {
if ((Mathf.Abs(givenPosition) + givenHeight > contentTop && Mathf.Abs(givenPosition) + givenHeight < contentBottom) || (Mathf.Abs(givenPosition) > contentTop && Mathf.Abs(givenPosition) < contentBottom)) {
if (canvasGroup.alpha != 1) {
canvasGroup.alpha = 1;
}
return true;
} else {
if (canvasGroup.alpha != 0) {
canvasGroup.alpha = 0;
}
return false;
}
}
static public void Setup(Scroll givenScroll) {
contentTop = (1 - givenScroll.verticalNormalizedPosition) * (givenScroll.content.rect.height - givenScroll.viewport.rect.height);
contentBottom = contentTop + givenScroll.viewport.rect.height;
}
}
SIX:
Unity's built in ScrollRect component allows for broad, modular functionality. However, in terms of performance it can be noticeably slower than if you were to write your own. Here is a Scroll script that achieves the same ends, but only supports the vertical, clamped and inertia properties of Unity's ScrollRect.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Scroll : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IScrollHandler {
private Camera mainCamera;
private RectTransform canvasRect;
public RectTransform viewport;
public RectTransform content;
private Rect viewportOld;
private Rect contentOld;
private List<Vector2> dragCoordinates = new List<Vector2>();
private List<float> offsets = new List<float>();
private int offsetsAveraged = 4;
private float offset;
private float velocity = 0;
private bool changesMade = false;
public float decelration = 0.135f;
public float scrollSensitivity;
public OnValueChanged onValueChanged;
[System.Serializable]
public class OnValueChanged : UnityEvent { }
[HideInInspector]
public float verticalNormalizedPosition
{
get
{
float sizeDelta = CaculateDeltaSize();
if (sizeDelta == 0) {
return 0;
} else {
return 1 - content.transform.localPosition.y / sizeDelta;
}
}
set
{
float o_verticalNormalizedPosition = verticalNormalizedPosition;
float m_verticalNormalizedPosition = Mathf.Max(0, Mathf.Min(1, value));
float maxY = CaculateDeltaSize();
content.transform.localPosition = new Vector3(content.transform.localPosition.x, Mathf.Max(0, (1 - m_verticalNormalizedPosition) * maxY), content.transform.localPosition.z);
float n_verticalNormalizedPosition = verticalNormalizedPosition;
if (o_verticalNormalizedPosition != n_verticalNormalizedPosition) {
onValueChanged.Invoke();
}
}
}
private float CaculateDeltaSize() {
return Mathf.Max(0, content.rect.height - viewport.rect.height); ;
}
private void Awake() {
mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
canvasRect = transform.root.GetComponent<RectTransform>();
}
private Vector2 ConvertEventDataDrag(PointerEventData eventData) {
return new Vector2(eventData.position.x / mainCamera.pixelWidth * canvasRect.rect.width, eventData.position.y / mainCamera.pixelHeight * canvasRect.rect.height);
}
private Vector2 ConvertEventDataScroll(PointerEventData eventData) {
return new Vector2(eventData.scrollDelta.x / mainCamera.pixelWidth * canvasRect.rect.width, eventData.scrollDelta.y / mainCamera.pixelHeight * canvasRect.rect.height) * scrollSensitivity;
}
public void OnPointerDown(PointerEventData eventData) {
velocity = 0;
dragCoordinates.Clear();
offsets.Clear();
dragCoordinates.Add(ConvertEventDataDrag(eventData));
}
public void OnScroll(PointerEventData eventData) {
UpdateOffsetsScroll(ConvertEventDataScroll(eventData));
OffsetContent(offsets[offsets.Count - 1]);
}
public void OnDrag(PointerEventData eventData) {
dragCoordinates.Add(ConvertEventDataDrag(eventData));
UpdateOffsetsDrag();
OffsetContent(offsets[offsets.Count - 1]);
}
public void OnPointerUp(PointerEventData eventData) {
dragCoordinates.Add(ConvertEventDataDrag(eventData));
UpdateOffsetsDrag();
OffsetContent(offsets[offsets.Count - 1]);
float totalOffsets = 0;
foreach (float offset in offsets) {
totalOffsets += offset;
}
velocity = totalOffsets / offsetsAveraged;
dragCoordinates.Clear();
offsets.Clear();
}
private void OffsetContent(float givenOffset) {
float newY = Mathf.Max(0, Mathf.Min(CaculateDeltaSize(), content.transform.localPosition.y + givenOffset));
if (content.transform.localPosition.y != newY) {
content.transform.localPosition = new Vector3(content.transform.localPosition.x, newY, content.transform.localPosition.z);
}
onValueChanged.Invoke();
}
private void UpdateOffsetsDrag() {
offsets.Add(dragCoordinates[dragCoordinates.Count - 1].y - dragCoordinates[dragCoordinates.Count - 2].y);
if (offsets.Count > offsetsAveraged) {
offsets.RemoveAt(0);
}
}
private void UpdateOffsetsScroll(Vector2 givenScrollDelta) {
offsets.Add(givenScrollDelta.y);
if (offsets.Count > offsetsAveraged) {
offsets.RemoveAt(0);
}
}
private void LateUpdate() {
if (viewport.rect != viewportOld) {
changesMade = true;
viewportOld = new Rect(viewport.rect);
}
if (content.rect != contentOld) {
changesMade = true;
contentOld = new Rect(content.rect);
}
if (velocity != 0) {
changesMade = true;
velocity = (velocity / Mathf.Abs(velocity)) * Mathf.FloorToInt(Mathf.Abs(velocity) * (1 - decelration));
offset = velocity;
}
if (changesMade) {
OffsetContent(offset);
changesMade = false;
offset = 0;
}
}
}
A nice article explains that the default targetFrameRate might be responsible for the unsmooth scrolling behavior of the scrollView. This can be resolved via:
Application.targetFrameRate = 60; // or whatever you wish. 60 turned out enough for us
Of course this setting is only effective if you have resolved the performance issues (as it is nicely explained by Phedg1).

How to set texture to automatically match with a change in window size by using same texture

I made a small 2D game by using unity3D(5.0.2f1). I dragged in some textures to use as the background in a scene. It worked well in the Unity Editor, but not when I built and ran it in a different window size. It didn't look as what I had seen in Unity Editor.
What should I do to change the texture size automatically when window size changes? Here is a screenshot of how the image looks in the editor and the build, as well as my build settings:
Maybe these will help!
//file ExtensionsHandy.cs
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public static class ExtensionsHandy
{
public static float OrthoScreenWidth(this Camera c)
{
return
c.ViewportToWorldPoint(new Vector3(1,1,10)).x
- c.ViewportToWorldPoint(new Vector3(0,1,10)).x;
}
public static float OrthoScreenHeight(this Camera c)
{
return
c.ViewportToWorldPoint(new Vector3(0,1,10)).y
- c.ViewportToWorldPoint(new Vector3(0,0,10)).y;
}
}
try like this
void Start()
{
float w = Camera.main.OrthoScreenWidth();
Debug.Log("w is " +w.ToString("f4");
}
Note. If not familiar with "extensions": quick tutorial.
Here are more very handy extensions for you.
These will actually move an object to the screen points!
For example,
transform.ScreenRight();
transform.ScreenTop();
the object, is now at the top-right of the screen!!!
And consider this ......
void Update()
{
transform.ScreenRight();
}
In that example: even if the user changes the orientation of the device, even if the user resizes the screen (Mac or Windows), the object is ALWAYS on the right of the screen!!
public static Vector3 WP( this Camera c, float x, float y, float z)
{
return c.ViewportToWorldPoint(new Vector3(x,y,z));
}
public static void ScreenLeft(this GameObject moveme)
{
Vector3 rr = moveme.transform.position;
Vector3 leftTop = Camera.main.WP(0f,1f,0f);
float leftX = leftTop.x;
rr.x = leftX;
moveme.transform.position = rr;
}
public static void ScreenRight(this GameObject moveme)
{
Vector3 rr = moveme.transform.position;
Vector3 rightTop = Camera.main.WP(1f,1f,0f);
float rightX = rightTop.x;
rr.x = rightX;
moveme.transform.position = rr;
}
public static void ScreenBottom(this GameObject moveme)
{
Vector3 rr = moveme.transform.position;
Vector3 bottomLeft = Camera.main.WP(0f,0f,0f);
float bottomY = bottomLeft.y;
rr.y = bottomY;
moveme.transform.position = rr;
}
public static void ScreenTop(this GameObject moveme)
{
Vector3 rr = moveme.transform.position;
Vector3 topLeft = Camera.main.WP(0f,1f,0f);
float topY = topLeft.y;
rr.y = topY;
moveme.transform.position = rr;
}
Hope it helps.....

Touch and Drag Sprite in Andengine

I'm trying to make a sprite so when you touch it and drag your finger, the sprite follows your movement. I've tried to follow the AndEngine examples, but they are part of GLES1. I'm using GLES2.
Within my code, the onAreaTouched is being called, but it is not continuously being called to update the sprite with my finger.
Thanks in advance.
public class RectangleFactory extends Sprite {
public float randomNumber;
public RectangleFactory(float pX, float pY, ITextureRegion pTextureRegion,
VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
// TODO Auto-generated constructor stub
Random random = new Random();
randomNumber = (float) random.nextInt(BallShakeActivity.CAMERA_WIDTH);
};
#Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float X, float Y)
{
Log.d("Mark", "circles are touched");
this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
if(pSceneTouchEvent.isActionMove()){
Log.d("Mark", "finger is moving");
}
return true;
};
#Override
protected void onManagedUpdate(final float pSecondsElapsed){
if(this.mY > 0f){
}
else{
Random random = new Random();
randomNumber = (float) random.nextInt(BallShakeActivity.CAMERA_WIDTH);
this.setPosition(randomNumber, 800f);
}
super.onManagedUpdate(pSecondsElapsed);
}
}
You can find some examples, including a touch-drag example, for AndEngine GLES2 in the AndEngineExamples repository on Nicolas' Github page.
https://github.com/nicolasgramlich/AndEngineExamples
The examples seem to be mostly for the GLES2 branch but there may also be some examples for the GLES2-AnchorCenter branch as well.
Some of the code works with GLES1/master branch but you're mostly on your own for examples for that branch.

Need help on Android car game [closed]

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

How to draw faster? SurfaceView, SurfaceHolder dirty rect

I have a problem with SurfaceView.
Function DrawWave is call by a timer Interval 5ms, BUT actually it needs more than 30ms between two calls, (I tried delete drawColor, drawPath).
I tried as "Mode 1" and "Mode 2", by using Dirty rect, hope it can run faster. The Interval is the same, both more than 30ms, (The width of this is 800px, and eScrX-sScrX<20px)
Question 1: Is it something I do wrong, using SurfaceView/SurfaceHolder?
Question 2: What can I do to improve the drawing speed? I hope that it can finish drawing in 10 ms.
My code:
public class VS_VChannel extends SurfaceView
{//Wave Show Class
//-------------------------------------------------------------------------------
private Paint paint = new Paint();
private SurfaceHolder sHolder = null;
private Canvas cvs = null;
private Path P = new Path();
//Data source of the wave point Y
protected VSChannel Channel = null;
private float drawY;
//-------------------------------------------------------------------------------
public VS_VChannel(Context context)
{
super(context);
}
//------------------------------------------------------------------------------
public VS_VChannel(Context context, AttributeSet attrs)
{
super(context, attrs);
//Bind the wave data source whith AttributeSet name:vs_wave
String vsName = attrs.getAttributeValue(null, "vs_wave");
Channel = (VSChannel)VS.GetItem(vsName);//Find the wave data source from collection with name
//
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(Channel.getColor());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
//
sHolder = this.getHolder();
this.setZOrderOnTop(true);
sHolder.setFormat(PixelFormat.TRANSPARENT);
}
//------------------------------------------------------------------------------
/** DrawWave is Call by a timer Interval 5ms,
* BUT actually it need more than 30ms between twice call,(tried delete drawColor, drawPath)
* I try as "Mode 1" and "Mode 2", by using Dirty rect, hope it can run faster
* The Interval is the same, both more than 30ms,
* (The width of this is 800px, and eScrX-sScrX<20px)
*/
protected void DrawWave(int sScrX, int eScrX)
{
Rect rect = new Rect(sScrX, 0, eScrX+8, getHeight()); //Mode 1
//Rect rect = new Rect(0, 0, getWidth(), getHeight()); //Mode 2
//
cvs = sHolder.lockCanvas(rect);
cvs.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
cvs.drawPath(P, paint);
sHolder.unlockCanvasAndPost(cvs);
}
//-------------------------------------------------------------------------------
protected void GetWaveY()
{
drawY = Channel.GetWaveY(getHeight());
}
//-------------------------------------------------------------------------------
protected void MoveTo(float x)
{
P.moveTo(x, drawY);
}
//-------------------------------------------------------------------------------
protected void LineTo(float x)
{
P.lineTo(x, drawY);
}
//-------------------------------------------------------------------------------
protected void DrawReturn()
{
P.reset();//Clear
P.moveTo(0, drawY);
}
//-------------------------------------------------------------------------------
}
//-------------------------------------------------------------------------------
If you are running on top of the display thread, you can only process and draw as fast as that thread allows. I might suggest drawing to a bitmap in another thread and then using the surface holder to unlock, draw the bitmap, and post.