hi i am new to processing and i'm trying to figure out how to make the sphere move from left to right using a marker instead of the mouse. can you help me please? i can use the marker to shoot but i cant move the sphere by shooting
import TUIO.*;
TuioProcessing tuioClient;
HashMap symbols=new HashMap();
PFont fontA;
int sphereDiameter = 50;
boolean shoot = false;
float obj_size = 60;
int randx()
{
return int(random(600));
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
int[] sphereYCoords = { 0, 0, 0, 0, 0 };
void setup()
{
size(1000,700);
tuioClient = new TuioProcessing(this);
}
void draw()
{
Vector<TuioObject> tuioObjectList =tuioClient.getTuioObjects();
Collections.sort(tuioObjectList, comp);
for (TuioObject tobj:tuioObjectList) {
fill(50, 50, 100);
int id = tobj.getSymbolID();
int x = tobj.getScreenX(width);
int y = tobj.getScreenY(height);
rect(x, y, obj_size, obj_size);
String txt="?";
if (symbols.containsKey(id)) {// if it's one in symbols, then look it up
txt = (String)symbols.get(id);
}
fill(255);
text(txt, x, y);
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
fill(100, 0, 0);
// draw the answer box
// ellipse(answerX, answerY, obj_size, obj_size);
fill(255);
// write the answer text
// text(""+answer, answerX, answerY);
background(1);
fill(color(255,255,0));
stroke(color(0,255,0));
triangle(mouseX-8, 580, mouseX+8, 580, mouseX, 565);
fill(color(255,0,0));
stroke(color(255,0,0));
if(shoot==true)
{
sphereKiller( mouseX);
shoot = false;
}
sphereDropper();
//gameEnder();
}
Comparator<TuioObject> comp = new Comparator<TuioObject>() {
// Comparator object to compare two TuioObjects on the basis of their x position
// Returns -1 if o1 left of o2; 0 if they have same x pos; 1 if o1 right of o2
public int compare(TuioObject o1, TuioObject o2) {
if (o1.getX()<o2.getX()) {
return -1;
}
else if (o1.getX()>o2.getX()) {
return 1;
}
else {
return 0;
}
}
};
void mousePressed()
{
shoot = true;
}
void sphereDropper()
{
stroke(255);
fill(255);
for (int i=0; i<5; i++)
{
ellipse(sphereXCoords[i], sphereYCoords[i]++,
sphereDiameter, sphereDiameter);
}
}
void sphereKiller(int shotX)
{
boolean hit = false;
for (int i = 0; i < 5; i++)
{
if((shotX >= (sphereXCoords[i]-sphereDiameter/2)) &&
(shotX <= (sphereXCoords[i]+sphereDiameter/2)))
{
hit = true;
line(mouseX, 565, mouseX, sphereYCoords[i]);
ellipse(sphereXCoords[i], sphereYCoords[i],
sphereDiameter+25, sphereDiameter+25);
sphereXCoords[i] = randx();
sphereYCoords[i] = 0;
}
}
if(hit == false)
{
line(mouseX, 565, mouseX, 0);
}
}
/* void gameEnder()
{
for (int i=0; i< 5; i++)
{
if(sphereYCoords[i]==600)
{
fill(color(255,0,0));
noLoop();
}
}
}*/
void addTuioObject(TuioObject tobj) {
}
// called when an object is removed from the scene
void removeTuioObject(TuioObject tobj) {
}
/ / called when an object is moved
void updateTuioObject (TuioObject tobj) {
if(tobj.getSymbolID() == 32)
{
shoot = true;
}
}
// called when a cursor is added to the scene
void addTuioCursor(TuioCursor tcur) {
}
// called when a cursor is moved
void updateTuioCursor (TuioCursor tcur) {
}
// called when a cursor is removed from the scene
void removeTuioCursor(TuioCursor tcur) {
}
// called after each message bundle
// representing the end of an image frame
void refresh(TuioTime bundleTime) {
//redraw();
}
What do you mean by "shooting" ?
So you have your tuioClient and you initialize it in setup(). Thats good, because then the callback methods (addTuioObject, removeTuioObject, updateTuioObject, addTuioCursor, updateTuioCursor, removeTuioCursor, refresh) will fire whenever your sketch receives a TUIO message.
Keep in mind that TUIO is based on OSC which is transported over UDP. That means the tracker (reactivision & co) will have to send to the IP and port your sketch is listening to. If both are on the same machine use 127.0.0.1 and port 3333 (default).
Have a look at the examples. You'll find them in the processing "IDE" click:
"File -> Examples"
and Navigate to
"Contributed Libraries -> TUIO"
Related
Implementing the Webview based application for Android TV with no of links to the website landing on Video pages. The web page being desktop, it is very difficult to use the D-Pad keys to navigate. I would like to implement the Mouse cursor kind of navigation controlled by D-Pad. Any help to available sample source code would help.
Trying to do the same thing here.
Basic approach:
Create a custom view that draws, moves and animates a cursor
In a Frame Layout add this custom cursor view on top of your webview
When the user clicks (key: DPAD center), simulate a click on the position of your cursor via simulated touch events
Scroll the WebView on a corresponding button press when the cursor is at the edge
The focus handling is a bit of a PITA when doing this, though:
The webview does all kinds of weird stuff (scrolling, highlighting,...) when it has focus. So I tried having my cursor view focused. Works perfectly fine, except when it comes to clicking text input fields -> keyboard won't show/work if the WebView isn't focused.
So, using getHitTestResult() we can find out if our click will hit an input field and make the WebView have focus before. That works fine, but I haven't yet found a reliable way to hand the focus back to my cursor view when the user is done entering text.
One thing I tried was getting a hook on the IME connection, but I couldn't quite get this approach to be stable enough for using it in a public app.
To Enable cursor pointer in android tv webview by creating custom pointer layout
public class CursorLayout extends FrameLayout {
public static final int CURSOR_DISAPPEAR_TIMEOUT = 5000;
public static int CURSOR_RADIUS = 0;
public static float CURSOR_STROKE_WIDTH = 0.0f;
public static float MAX_CURSOR_SPEED = 0.0f;
public static int SCROLL_START_PADDING = 100;
public static final int UNCHANGED = -100;
public int EFFECT_DIAMETER;
public int EFFECT_RADIUS;
private Callback callback;
/* access modifiers changed from: private */
public Point cursorDirection = new Point(0, 0);
/* access modifiers changed from: private */
public Runnable cursorHideRunnable = new Runnable() {
public void run() {
CursorLayout.this.invalidate();
}
};
/* access modifiers changed from: private */
public PointF cursorPosition = new PointF(0.0f, 0.0f);
/* access modifiers changed from: private */
public PointF cursorSpeed = new PointF(0.0f, 0.0f);
private Runnable cursorUpdateRunnable = new Runnable() {
public void run() {
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().removeCallbacks(CursorLayout.this.cursorHideRunnable);
}
long currentTimeMillis = System.currentTimeMillis();
long access$100 = currentTimeMillis - CursorLayout.this.lastCursorUpdate;
CursorLayout.this.lastCursorUpdate = currentTimeMillis;
float f = ((float) access$100) * 0.05f;
PointF access$200 = CursorLayout.this.cursorSpeed;
CursorLayout cursorLayout = CursorLayout.this;
float f2 = cursorLayout.cursorSpeed.x;
CursorLayout cursorLayout2 = CursorLayout.this;
float access$400 = cursorLayout.bound(f2 + (cursorLayout2.bound((float) cursorLayout2.cursorDirection.x, 1.0f) * f), CursorLayout.MAX_CURSOR_SPEED);
CursorLayout cursorLayout3 = CursorLayout.this;
float f3 = cursorLayout3.cursorSpeed.y;
CursorLayout cursorLayout4 = CursorLayout.this;
access$200.set(access$400, cursorLayout3.bound(f3 + (cursorLayout4.bound((float) cursorLayout4.cursorDirection.y, 1.0f) * f), CursorLayout.MAX_CURSOR_SPEED));
if (Math.abs(CursorLayout.this.cursorSpeed.x) < 0.1f) {
CursorLayout.this.cursorSpeed.x = 0.0f;
}
if (Math.abs(CursorLayout.this.cursorSpeed.y) < 0.1f) {
CursorLayout.this.cursorSpeed.y = 0.0f;
}
if (CursorLayout.this.cursorDirection.x == 0 && CursorLayout.this.cursorDirection.y == 0 && CursorLayout.this.cursorSpeed.x == 0.0f && CursorLayout.this.cursorSpeed.y == 0.0f) {
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().postDelayed(CursorLayout.this.cursorHideRunnable, 5000);
}
return;
}
CursorLayout.this.tmpPointF.set(CursorLayout.this.cursorPosition);
CursorLayout.this.cursorPosition.offset(CursorLayout.this.cursorSpeed.x, CursorLayout.this.cursorSpeed.y);
Log.d("cursor1234_xxxx", String.valueOf(CursorLayout.this.cursorPosition.x));
Log.d("cursor1234_yyyy", String.valueOf(CursorLayout.this.cursorPosition.y));
if (CursorLayout.this.cursorPosition.x < 0.0f) {
CursorLayout.this.cursorPosition.x = 0.0f;
} else if (CursorLayout.this.cursorPosition.x > ((float) (CursorLayout.this.getWidth() - 1))) {
CursorLayout.this.cursorPosition.x = (float) (CursorLayout.this.getWidth() - 1);
}
if (CursorLayout.this.cursorPosition.y < 0.0f) {
CursorLayout.this.cursorPosition.y = 0.0f;
} else if (CursorLayout.this.cursorPosition.y > ((float) (CursorLayout.this.getHeight() - 1))) {
CursorLayout.this.cursorPosition.y = (float) (CursorLayout.this.getHeight() - 1);
}
if (!CursorLayout.this.tmpPointF.equals(CursorLayout.this.cursorPosition) && CursorLayout.this.dpadCenterPressed) {
CursorLayout cursorLayout5 = CursorLayout.this;
cursorLayout5.dispatchMotionEvent(cursorLayout5.cursorPosition.x, CursorLayout.this.cursorPosition.y, 2);
}
View childAt = CursorLayout.this.getChildAt(0);
if (childAt != null) {
if (CursorLayout.this.cursorPosition.y > ((float) (CursorLayout.this.getHeight() - CursorLayout.SCROLL_START_PADDING))) {
if (CursorLayout.this.cursorSpeed.y > 0.0f && childAt.canScrollVertically((int) CursorLayout.this.cursorSpeed.y)) {
childAt.scrollTo(childAt.getScrollX(), childAt.getScrollY() + ((int) CursorLayout.this.cursorSpeed.y));
}
} else if (CursorLayout.this.cursorPosition.y < ((float) CursorLayout.SCROLL_START_PADDING) && CursorLayout.this.cursorSpeed.y < 0.0f && childAt.canScrollVertically((int) CursorLayout.this.cursorSpeed.y)) {
childAt.scrollTo(childAt.getScrollX(), childAt.getScrollY() + ((int) CursorLayout.this.cursorSpeed.y));
}
if (CursorLayout.this.cursorPosition.x > ((float) (CursorLayout.this.getWidth() - CursorLayout.SCROLL_START_PADDING))) {
if (CursorLayout.this.cursorSpeed.x > 0.0f && childAt.canScrollHorizontally((int) CursorLayout.this.cursorSpeed.x)) {
childAt.scrollTo(childAt.getScrollX() + ((int) CursorLayout.this.cursorSpeed.x), childAt.getScrollY());
}
} else if (CursorLayout.this.cursorPosition.x < ((float) CursorLayout.SCROLL_START_PADDING) && CursorLayout.this.cursorSpeed.x < 0.0f && childAt.canScrollHorizontally((int) CursorLayout.this.cursorSpeed.x)) {
childAt.scrollTo(childAt.getScrollX() + ((int) CursorLayout.this.cursorSpeed.x), childAt.getScrollY());
}
}
CursorLayout.this.invalidate();
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().post(this);
}
}
};
/* access modifiers changed from: private */
public boolean dpadCenterPressed = false;
/* access modifiers changed from: private */
public long lastCursorUpdate = System.currentTimeMillis();
private Paint paint = new Paint();
PointF tmpPointF = new PointF();
public interface Callback {
void onUserInteraction();
}
/* access modifiers changed from: private */
public float bound(float f, float f2) {
if (f > f2) {
return f2;
}
float f3 = -f2;
return f < f3 ? f3 : f;
}
public CursorLayout(Context context) {
super(context);
init();
}
public CursorLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
private void init() {
if (!isInEditMode()) {
this.paint.setAntiAlias(true);
setWillNotDraw(false);
Display defaultDisplay = ((WindowManager) getContext().getSystemService(getContext().WINDOW_SERVICE)).getDefaultDisplay();
Point point = new Point();
defaultDisplay.getSize(point);
this.EFFECT_RADIUS = point.x / 20;
this.EFFECT_DIAMETER = this.EFFECT_RADIUS * 2;
CURSOR_STROKE_WIDTH = (float) (point.x / 400);
CURSOR_RADIUS = point.x / 110;
MAX_CURSOR_SPEED = (float) (point.x / 25);
SCROLL_START_PADDING = point.x / 15;
}
}
public void setCallback(Callback callback2) {
this.callback = callback2;
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
Callback callback2 = this.callback;
if (callback2 != null) {
callback2.onUserInteraction();
}
return super.onInterceptTouchEvent(motionEvent);
}
/* access modifiers changed from: protected */
public void onSizeChanged(int i, int i2, int i3, int i4) {
super.onSizeChanged(i, i2, i3, i4);
UtilMethods.LogMethod("cursorView123_", "onSizeChanged");
if (!isInEditMode()) {
this.cursorPosition.set(((float) i) / 2.0f, ((float) i2) / 2.0f);
if (getHandler() != null) {
getHandler().postDelayed(this.cursorHideRunnable, 5000);
}
}
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
UtilMethods.LogMethod("cursorView123_", "dispatchKeyEvent");
Callback callback2 = this.callback;
if (callback2 != null) {
callback2.onUserInteraction();
}
int keyCode = keyEvent.getKeyCode();
if (!(keyCode == 66 || keyCode == 160)) {
switch (keyCode) {
case 19:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.y <= 0.0f) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -100, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, -100, 0, false);
}
return true;
case 20:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.y >= ((float) getHeight())) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -100, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, -100, 0, false);
}
return true;
case 21:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.x <= 0.0f) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -1, -100, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, -100, false);
}
return true;
case 22:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.x >= ((float) getWidth())) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, 1, -100, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, -100, false);
}
return true;
case 23:
break;
default:
switch (keyCode) {
case 268:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, -1, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 269:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, -1, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 270:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, 1, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 271:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, 1, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
}
}
}
if (!isCursorDissappear()) {
if (keyEvent.getAction() == 0 && !getKeyDispatcherState().isTracking(keyEvent)) {
getKeyDispatcherState().startTracking(keyEvent, this);
this.dpadCenterPressed = true;
dispatchMotionEvent(this.cursorPosition.x, this.cursorPosition.y, 0);
} else if (keyEvent.getAction() == 1) {
getKeyDispatcherState().handleUpEvent(keyEvent);
dispatchMotionEvent(this.cursorPosition.x, this.cursorPosition.y, 1);
this.dpadCenterPressed = false;
}
return true;
}
return super.dispatchKeyEvent(keyEvent);
}
/* access modifiers changed from: private */
public void dispatchMotionEvent(float f, float f2, int i) {
UtilMethods.LogMethod("cursorView123_", "dispatchMotionEvent");
long uptimeMillis = SystemClock.uptimeMillis();
long uptimeMillis2 = SystemClock.uptimeMillis();
PointerProperties pointerProperties = new PointerProperties();
pointerProperties.id = 0;
pointerProperties.toolType = 1;
PointerProperties[] pointerPropertiesArr = {pointerProperties};
PointerCoords pointerCoords = new PointerCoords();
pointerCoords.x = f;
pointerCoords.y = f2;
pointerCoords.pressure = 1.0f;
pointerCoords.size = 1.0f;
dispatchTouchEvent(MotionEvent.obtain(uptimeMillis, uptimeMillis2, i, 1, pointerPropertiesArr, new PointerCoords[]{pointerCoords}, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0));
}
private void handleDirectionKeyEvent(KeyEvent keyEvent, int i, int i2, boolean z) {
this.lastCursorUpdate = System.currentTimeMillis();
if (!z) {
getKeyDispatcherState().handleUpEvent(keyEvent);
this.cursorSpeed.set(0.0f, 0.0f);
} else if (!getKeyDispatcherState().isTracking(keyEvent)) {
Handler handler = getHandler();
handler.removeCallbacks(this.cursorUpdateRunnable);
handler.post(this.cursorUpdateRunnable);
getKeyDispatcherState().startTracking(keyEvent, this);
} else {
return;
}
Point point = this.cursorDirection;
if (i == -100) {
i = point.x;
}
if (i2 == -100) {
i2 = this.cursorDirection.y;
}
point.set(i, i2);
}
/* access modifiers changed from: protected */
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
UtilMethods.LogMethod("cursorView123_", "dispatchDraw");
if (!isInEditMode() && !isCursorDissappear()) {
float f = this.cursorPosition.x;
float f2 = this.cursorPosition.y;
this.paint.setColor(Color.argb(128, 255, 255, 255));
this.paint.setStyle(Style.FILL);
canvas.drawCircle(f, f2, (float) CURSOR_RADIUS, this.paint);
this.paint.setColor(-7829368);
this.paint.setStrokeWidth(CURSOR_STROKE_WIDTH);
this.paint.setStyle(Style.STROKE);
canvas.drawCircle(f, f2, (float) CURSOR_RADIUS, this.paint);
}
}
private boolean isCursorDissappear() {
return System.currentTimeMillis() - this.lastCursorUpdate > 5000;
}
/* access modifiers changed from: protected */
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
}}
then put the webview inside custom cursor layout in XML
<com.example.webviewtvapp.CursorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/cursorLayout">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.example.webviewtvapp.CursorLayout>
I have a level loading script that draws a level from an array representation loaded from file. This works fine in unity editor but when I build for ios those objects dynamically drawn do not display.
Here is the code that does the drawing:
void DrawNewLevel(int level) {
LevelEditor.Level lvl = new LevelEditor.Level (1, level);
for (int x = 0; x < 260; x++) {
for (int y = 0; y < 23; y++) {
GameObject gameObject;
if (lvl.LevelContents[x, y].BlockType != LevelEditor.BlockType.Empty) {
Debug.Log("drawing non-null");
if (lvl.LevelContents[x, y].BlockType == LevelEditor.BlockType.Floor) {
gameObject = Instantiate(Floor);
gameObject.transform.position = new Vector3(x, 23-y, 0);
} else if (lvl.LevelContents[x, y].BlockType == LevelEditor.BlockType.FloorBad) {
gameObject = Instantiate(FloorBad);
gameObject.transform.position = new Vector3(x, 23-y, 0);
} else if (lvl.LevelContents[x, y].BlockType == LevelEditor.BlockType.SmartRocketLauncher) {
gameObject = Instantiate(SmartRocketLauncher);
gameObject.transform.position = new Vector3(x, 23-y, 1);
}
}
}
}
}
This program is about driving fast and dodging the obstacles. I followed a couple of tutorials and managed to create an explosion class. Whenever a collision occurs, the explosion is meant to appear, but it doesn't.
There is no error, but I think the problem is in the Game1.cs. I created the following functions in the Game1.cs:
//list
List <Explosion> explosionList = new List<Explosion>();
//This is in the update method
foreach (Explosion ex in explosionList)
{
ex.Update(gameTime);
}
//This is a method called manage explosions
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
//This is placed in the CheckCollision method
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(theHazard.Position.X, theHazard.Position.Y)));
Game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace DriveFast
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Texture2D mCar;
private Texture2D mBackground;
private Texture2D mRoad;
private Texture2D mHazard;
private Texture2D hazardCrash;
private KeyboardState mPreviousKeyboardState;
private Vector2 mCarPosition = new Vector2(280, 440);
private int mMoveCarX = 160;
private int mVelocityY;
private double mNextHazardAppearsIn;
private int mCarsRemaining;
private int mHazardsPassed;
private int mIncreaseVelocity;
private double mExitCountDown = 10;
private int[] mRoadY = new int[2];
private List<Hazard> mHazards = new List<Hazard>();
private Random mRandom = new Random();
private SpriteFont mFont;
//video
List <Explosion> explosionList = new List<Explosion>();
private enum State
{
TitleScreen,
Running,
Crash,
GameOver,
Success
}
private State mCurrentState = State.TitleScreen;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
mCar = Content.Load<Texture2D>("Images/Car");
mBackground = Content.Load<Texture2D>("Images/Background");
mRoad = Content.Load<Texture2D>("Images/Road");
mHazard = Content.Load<Texture2D>("Images/Hazard");
hazardCrash = Content.Load<Texture2D>("Images/hazardCrash");
mFont = Content.Load<SpriteFont>("MyFont");
}
protected override void UnloadContent()
{
}
protected void StartGame()
{
mRoadY[0] = 0;
mRoadY[1] = -1 * mRoad.Height;
mHazardsPassed = 0;
mCarsRemaining = 3;
mVelocityY = 3;
mNextHazardAppearsIn = 1.5;
mIncreaseVelocity = 5;
mHazards.Clear();
mCurrentState = State.Running;
}
protected override void Update(GameTime gameTime)
{
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
//Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
aCurrentKeyboardState.IsKeyDown(Keys.Escape) == true)
{
this.Exit();
}
switch (mCurrentState)
{
case State.TitleScreen:
case State.Success:
case State.GameOver:
{
ExitCountdown(gameTime);
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
StartGame();
}
break;
}
case State.Running:
{
//If the user has pressed the Spacebar, then make the car switch lanes
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
mCarPosition.X += mMoveCarX;
mMoveCarX *= -1;
}
ScrollRoad();
foreach (Hazard aHazard in mHazards)
{
if (CheckCollision(aHazard) == true)
{
//video
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(aHazard.Position.X, aHazard.Position.Y)));
break;
}
MoveHazard(aHazard);
}
UpdateHazards(gameTime);
break;
}
case State.Crash:
{
//If the user has pressed the Space key, then resume driving
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
mHazards.Clear();
mCurrentState = State.Running;
}
break;
}
}
mPreviousKeyboardState = aCurrentKeyboardState;
//video
ManageExplosions();
//
base.Update(gameTime);
//video
foreach (Explosion ex in explosionList)
{
ex.Update(gameTime);
}
}
private void ScrollRoad()
{
//Move the scrolling Road
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
if (mRoadY[aIndex] >= this.window.ClientBounds.Height)
{
int aLastRoadIndex = aIndex;
for (int aCounter = 0; aCounter < mRoadY.Length; aCounter++)
{
if (mRoadY[aCounter] < mRoadY[aLastRoadIndex])
{
aLastRoadIndex = aCounter;
}
}
mRoadY[aIndex] = mRoadY[aLastRoadIndex] - mRoad.Height;
}
}
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
mRoadY[aIndex] += mVelocityY;
}
}
private void MoveHazard(Hazard theHazard)
{
theHazard.Position.Y += mVelocityY;
if (theHazard.Position.Y > graphics.GraphicsDevice.Viewport.Height && theHazard.Visible == true)
{
theHazard.Visible = false;
mHazardsPassed += 1;
if (mHazardsPassed >= 100)
{
mCurrentState = State.Success;
mExitCountDown = 10;
}
mIncreaseVelocity -= 1;
if (mIncreaseVelocity < 0)
{
mIncreaseVelocity = 5;
mVelocityY += 1;
}
}
}
private void UpdateHazards(GameTime theGameTime)
{
mNextHazardAppearsIn -= theGameTime.ElapsedGameTime.TotalSeconds;
if (mNextHazardAppearsIn < 0)
{
int aLowerBound = 24 - (mVelocityY * 2);
int aUpperBound = 30 - (mVelocityY * 2);
if (mVelocityY > 10)
{
aLowerBound = 6;
aUpperBound = 8;
}
mNextHazardAppearsIn = (double)mRandom.Next(aLowerBound, aUpperBound) / 10;
AddHazard();
}
}
private void AddHazard()
{
int aRoadPosition = mRandom.Next(1, 3);
int aPosition = 275;
if (aRoadPosition == 2)
{
aPosition = 440;
}
bool aAddNewHazard = true;
foreach (Hazard aHazard in mHazards)
{
if (aHazard.Visible == false)
{
aAddNewHazard = false;
aHazard.Visible = true;
aHazard.Position = new Vector2(aPosition, -mHazard.Height);
break;
}
}
if (aAddNewHazard == true)
{
//Add a hazard to the left side of the Road
Hazard aHazard = new Hazard();
aHazard.Position = new Vector2(aPosition, -mHazard.Height);
mHazards.Add(aHazard);
}
}
private bool CheckCollision(Hazard theHazard)
{
BoundingBox aHazardBox = new BoundingBox(new Vector3(theHazard.Position.X, theHazard.Position.Y, 0), new Vector3(theHazard.Position.X + (mHazard.Width * .4f), theHazard.Position.Y + ((mHazard.Height - 50) * .4f), 0));
BoundingBox aCarBox = new BoundingBox(new Vector3(mCarPosition.X, mCarPosition.Y, 0), new Vector3(mCarPosition.X + (mCar.Width * .2f), mCarPosition.Y + (mCar.Height * .2f), 0));
if (aHazardBox.Intersects(aCarBox) == true)
{
//video
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(theHazard.Position.X, theHazard.Position.Y)));
mCurrentState = State.Crash;
mCarsRemaining -= 1;
if (mCarsRemaining < 0)
{
mCurrentState = State.GameOver;
mExitCountDown = 10;
}
return true;
}
return false;
}
private void ExitCountdown(GameTime theGameTime)
{
mExitCountDown -= theGameTime.ElapsedGameTime.TotalSeconds;
if (mExitCountDown < 0)
{
this.Exit();
}
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(mBackground, new Rectangle(graphics.GraphicsDevice.Viewport.X, graphics.GraphicsDevice.Viewport.Y, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height), Color.White);
foreach (Explosion ex in explosionList)
{
ex.Draw(spriteBatch);
}
switch (mCurrentState)
{
case State.TitleScreen:
{
//Draw the display text for the Title screen
DrawTextCentered("Drive and avoid the hazards!", 200);
DrawTextCentered("Press 'Space' to start", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 475);
break;
}
default:
{
DrawRoad();
DrawHazards();
spriteBatch.Draw(mCar, mCarPosition, new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0);
spriteBatch.DrawString(mFont, "Cars:", new Vector2(28, 520), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
for (int aCounter = 0; aCounter < mCarsRemaining; aCounter++)
{
spriteBatch.Draw(mCar, new Vector2(25 + (30 * aCounter), 550), new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.05f, SpriteEffects.None, 0);
}
spriteBatch.DrawString(mFont, "Hazards: " + mHazardsPassed.ToString(), new Vector2(5, 25), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
if (mCurrentState == State.Crash)
{
DrawTextDisplayArea();
DrawTextCentered("Crash!", 200);
DrawTextCentered("Press 'Space' to continue driving.", 260);
}
else if (mCurrentState == State.GameOver)
{
DrawTextDisplayArea();
DrawTextCentered("Game Over.", 200);
DrawTextCentered("Press 'Space' to re-try.", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 400);
}
else if (mCurrentState == State.Success)
{
DrawTextDisplayArea();
DrawTextCentered("Well Done!", 200);
DrawTextCentered("Press 'Space' to play again.", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 400);
}
break;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
private void DrawRoad()
{
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
if (mRoadY[aIndex] > mRoad.Height * -1 && mRoadY[aIndex] <= this.window.ClientBounds.Height)
{
spriteBatch.Draw(mRoad, new Rectangle((int)((this.window.ClientBounds.Width - mRoad.Width) / 2 - 18), mRoadY[aIndex], mRoad.Width, mRoad.Height + 5), Color.White);
}
}
}
private void DrawHazards()
{
foreach (Hazard aHazard in mHazards)
{
if (aHazard.Visible == true)
{
spriteBatch.Draw(mHazard, aHazard.Position, new Rectangle(0, 0, mHazard.Width, mHazard.Height), Color.White, 0, new Vector2(0, 0), 0.4f, SpriteEffects.None, 0);
}
}
}
private void DrawTextDisplayArea()
{
int aPositionX = (int)((graphics.GraphicsDevice.Viewport.Width / 2) - (450 / 2));
spriteBatch.Draw(mBackground, new Rectangle(aPositionX, 75, 450, 400), Color.White);
}
private void DrawTextCentered(string theDisplayText, int thePositionY)
{
Vector2 aSize = mFont.MeasureString(theDisplayText);
int aPositionX = (int)((graphics.GraphicsDevice.Viewport.Width / 2) - (aSize.X / 2));
spriteBatch.DrawString(mFont, theDisplayText, new Vector2(aPositionX, thePositionY), Color.Beige, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
spriteBatch.DrawString(mFont, theDisplayText, new Vector2(aPositionX + 1, thePositionY + 1), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
}
//video
//manage explosions
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
}
}
Explosion.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace DriveFast
{
public class Explosion
{
public Texture2D texture;
public Vector2 position;
public float timer;
public float interval;
public Vector2 origin;
public int currentFrame, spriteWidth, spriteHeight;
public Rectangle sourceRect;
public bool isVisible;
//Constructor
public Explosion(Texture2D newTexture, Vector2 newPosition)
{
position = newPosition;
texture = newTexture;
timer = 0;
interval = 20f;
currentFrame = 1;
spriteWidth = 128;
spriteHeight = 128;
isVisible = true;
}
//load content
public void LoadContent(ContentManager Content)
{
}
//update
public void Update(GameTime gameTime)
{
//increase
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
timer = 0f;
}
if (currentFrame == 17)
{
isVisible = false;
currentFrame = 0;
}
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
}
//draw
public void Draw(SpriteBatch spriteBatch)
{
if (isVisible == true)
{
spriteBatch.Draw(texture, position, sourceRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
}
}
}
}
Hazard.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace DriveFast
{
class Hazard
{
public Vector2 Position;
public bool Visible = true;
public Hazard()
{
}
}
}
First of all you need to draw your Explosions after road, car, hazards etc. Replace next code as shown below:
DrawRoad();
DrawHazards();
spriteBatch.Draw(mCar, mCarPosition, new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0);
// place code here
foreach (Explosion ex in explosionList)
{
ex.Draw(spriteBatch);
}
//
Into manage explosion method make !isVisible instead of isVisible:
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (!explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
Remove line:
foreach (Hazard aHazard in mHazards)
{
if (CheckCollision(aHazard) == true)
{
//remove next line because it is duplicate of adding Explosion which is already added inside CheckCollision(Hazard) method
//explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(aHazard.Position.X, aHazard.Position.Y)));
break;
}
MoveHazard(aHazard);
}
Change next variables:
spriteWidth = 71;//128;
spriteHeight = 100;//128;
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
//origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
origin = new Vector2(-(sourceRect.Width / 4), 0);
Comment next code for testing:
if (mCurrentState == State.Crash)
{
//DrawTextDisplayArea();
//DrawTextCentered("Crash!", 200);
//DrawTextCentered("Press 'Space' to continue driving.", 260);
}
I am making a game where characters come from opposite sides of the screen and collide and attack each other then they are removed when they die. I have managed to enable the lists to stop moving and do damage when they collide but my problem is when 2 of them collide all of them stop moving.
My code for the shortswordsman collisions is:
private void shortMoveCollisions(GameTime gameTime)
{
Rectangle shortRect;
int shortSpeed = 2;
int shortDamage = 20;
bool collided = false;
for (int i = 0; i < shortList.Count; i++)
{
List<Goblin> tempGoblinList = new List<Goblin>(goblinList);
shortRect = new Rectangle((int)shortList[i].position.X, (int)shortList[i].position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
foreach (Goblin goblin in tempGoblinList)
{
Rectangle goblinRect = new Rectangle((int)goblin.position.X, (int)goblin.position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
if (shortRect.Intersects(goblinRect))
{
collided = true;
shortList[i].AnimateAttack(gameTime);
shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (shortTimer >= shortDelay)
{
shortTimer -= shortDelay;
goblin.health -= shortDamage;
if (goblin.health <= 0)
{
goblinList.Remove(goblin);
}
}
}
}
if (shortRect.Intersects(background.badCastleRect))
{
collided = true;
shortList[i].AnimateAttack(gameTime);
shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (shortTimer >= shortDelay)
{
shortTimer -= shortDelay;
badCastleHealth -= shortDamage;
}
}
if (collided == false)
{
shortList[i].AnimateWalk(gameTime);
shortList[i].position.X += shortSpeed;
}
}
}
And my code for the goblins collisions is:
private void GoblinMoveCollisions(GameTime gameTime)
{
Rectangle goblinRect;
int goblinSpeed = 2;
int goblinDamage = 20;
bool collided = false;
for (int i = 0; i < goblinList.Count; i++)
{
List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);
goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
foreach (ShortSwordsman shortSwordsman in tempShortList)
{
Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
if (goblinRect.Intersects(shortRect))
{
collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
shortSwordsman.health -= goblinDamage;
if (shortSwordsman.health <= 0)
{
shortList.Remove(shortSwordsman);
}
}
}
}
if (goblinRect.Intersects(background.goodCastleRect))
{
collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
goodCastleHealth -= goblinDamage;
}
}
if (collided == false)
{
goblinList[i].AnimateWalk(gameTime);
goblinList[i].position.X -= goblinSpeed;
}
}
}
Your collided bool shouldn't be a variable of those classes, as those classes seem to operate on the entire lists of all the entities. Instead the collision detection should happen on an entity by entity basis, basically: make the collided bool a property of goblins and swordsmen. This would mean that you'll have to check for intersections with other creatures of the same type as well, probably without an attack command.
This is the code I am using at the moment - shortswordsman and goblin are the same so i will only show one:
In the goblin class:
public Goblin(Vector2 position, float health, bool Collided, Rectangle goblinRect)
{
this.position = position;
this.health = health;
this.Collided = Collided;
this.goblinRect = goblinRect;
}
In the game1 class:
void CreateGoblin()
{
goblinList.Add(new Goblin(new Vector2(1900, 270), 100, false, new Rectangle()));
}
And then for the collisions i tried this - this includes the bit to try and stop them overlapping each other:
private void GoblinMoveCollisions(GameTime gameTime)
{
int goblinSpeed = 2;
int goblinDamage = 20;
for (int i = 0; i < goblinList.Count; i++)
{
goblinList[i].Collided = false;
goblinList[i].goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);
foreach (ShortSwordsman shortSwordsman in tempShortList)
{
Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
if (goblinList[i].goblinRect.Intersects(shortRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
shortSwordsman.health -= goblinDamage;
if (shortSwordsman.health <= 0)
{
shortList.Remove(shortSwordsman);
}
}
}
}
if (goblinList[i].goblinRect.Intersects(background.goodCastleRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
goodCastleHealth -= goblinDamage;
}
}
if (goblinList[i].goblinRect.Intersects(goblinList[i].goblinRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateStill(gameTime);
}
if (goblinList[i].Collided == false)
{
goblinList[i].AnimateWalk(gameTime);
goblinList[i].position.X -= goblinSpeed;
}
}
}
I can able to show one location using co ordinates or longtitude and latitude but i dont know how to show more than one location in the blackberry MapField.If is it possible pls share with me how to do this..
Same way as How to show our own icon in BlackBerry Map?.
Pass an array of Coordinates into custom MapField, define a bitmap for location point and paint it for each Coordinate in custom MapField paint() method.
Remember to zoom in/out CustomMapField for best fit of all location points.
Sample of implementation
Lets display Liverpool Sheffield and London with custom bitmap icons (yellow circle with black border). Code for custom MapField:
class MultyMapField extends MapField {
Coordinates[] mPoints = new Coordinates[0];
Bitmap mPoint;
Bitmap mPointsBitmap;
XYRect mDest;
XYRect[] mPointDest;
public void addCoordinates(Coordinates coordinates) {
Arrays.add(mPoints, coordinates);
zoomToFitPoints();
repaintPoints();
}
protected void zoomToFitPoints() {
// zoom to max
setZoom(getMaxZoom());
// get pixels of all points
int minLeft = getWidth();
int minUp = getHeight();
int maxRight = 0;
int maxDown = 0;
Coordinates minLeftCoordinates = null;
Coordinates minUpCoordinates = null;
Coordinates maxRightCoordinates = null;
Coordinates maxDownCoordinates = null;
for (int i = 0; i < mPoints.length; i++) {
XYPoint point = new XYPoint();
convertWorldToField(mPoints[i], point);
if (point.x <= minLeft) {
minLeft = point.x;
minLeftCoordinates = mPoints[i];
}
if (point.x >= maxRight) {
maxRight = point.x;
maxRightCoordinates = mPoints[i];
}
if (point.y <= minUp) {
minUp = point.y;
minUpCoordinates = mPoints[i];
}
if (point.y >= maxDown) {
maxDown = point.y;
maxDownCoordinates = mPoints[i];
}
}
double moveToLat = maxDownCoordinates.getLatitude()
+ (minUpCoordinates.getLatitude() - maxDownCoordinates
.getLatitude()) / 2;
double moveToLong = minLeftCoordinates.getLongitude()
+ (maxRightCoordinates.getLongitude() - minLeftCoordinates
.getLongitude()) / 2;
Coordinates moveTo = new Coordinates(moveToLat, moveToLong, 0);
moveTo(moveTo);
// zoom to min left up, max right down pixels + 1
int zoom = getZoom();
boolean outOfBounds = false;
while (!outOfBounds && zoom > getMinZoom()) {
zoom--;
setZoom(zoom);
XYPoint point = new XYPoint();
try {
convertWorldToField(minLeftCoordinates, point);
if (point.x < 0)
outOfBounds = true;
convertWorldToField(minUpCoordinates, point);
if (point.y < 0)
outOfBounds = true;
convertWorldToField(maxRightCoordinates, point);
if (point.x > getWidth())
outOfBounds = true;
convertWorldToField(maxDownCoordinates, point);
if (point.y > getHeight())
outOfBounds = true;
} catch (IllegalArgumentException ex) {
outOfBounds = true;
}
}
zoom++;
setZoom(zoom);
}
protected void repaintPoints() {
mPointsBitmap = new Bitmap(getWidth(), getHeight());
mPointsBitmap.createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP);
mDest = new XYRect(0, 0, mPointsBitmap.getWidth(), mPointsBitmap
.getHeight());
Graphics g = new Graphics(mPointsBitmap);
if (null != mPoint) {
mPointDest = new XYRect[mPoints.length];
for (int i = 0; i < mPoints.length; i++) {
if (null == mPointDest[i]) {
XYPoint fieldOut = new XYPoint();
convertWorldToField(mPoints[i], fieldOut);
int imgW = mPoint.getWidth();
int imgH = mPoint.getHeight();
mPointDest[i] = new XYRect(fieldOut.x - imgW / 2,
fieldOut.y - imgH, imgW, imgH);
}
g.drawBitmap(mPointDest[i], mPoint, 0, 0);
}
}
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (null != mPointsBitmap) {
graphics.setGlobalAlpha(100);
graphics.drawBitmap(mDest, mPointsBitmap, 0, 0);
}
}
}
Sample of use:
class Scr extends MainScreen {
// test coordinates:
// London
// 51.507778, -0.128056
Coordinates mLondonC = new Coordinates(51.507778, -0.128056, 0);
// Liverpool
// 53.4, -2.983333
Coordinates mLiverpoolC = new Coordinates(53.4, -2.983333, 0);
// Sheffield
// 53.385833, -1.469444
Coordinates mSheffieldC = new Coordinates(53.385833, -1.469444, 0);
MultyMapField mMultyMapField;
public Scr() {
add(mMultyMapField = new MultyMapField());
mMultyMapField.mPoint = createPointBitmap();
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
mMultyMapField.addCoordinates(mLondonC);
mMultyMapField.addCoordinates(mLiverpoolC);
mMultyMapField.addCoordinates(mSheffieldC);
}
}
private Bitmap createPointBitmap() {
int r = 10;
Bitmap result = new Bitmap(2 * r, 2 * r);
result.createAlpha(Bitmap.ALPHA_BITDEPTH_8BPP);
Graphics g = new Graphics(result);
g.setColor(Color.BLACK);
g.fillEllipse(r, r, 2 * r, r, r, 2 * r, 0, 360);
g.setColor(Color.YELLOW);
g.fillEllipse(r, r, r + (r - 2), r, r, r + (r - 2), 0, 360);
return result;
}
}
A valid and probably simpler option would be to use this open source library by Monits https://github.com/Monits/blackberry-commons
It contains several common functionality found in BB applications and is compatible for BB 4.6.1+
Among other things, it provides a map field with the ability to add and display markers on top of it, with and without focus, and optionally "open" them. This makes for an API much more alike that found on other smart phones such as iPhone or Android.
The documentation is pretty good, and the wiki even has a tutorial on how to achieve it https://github.com/Monits/blackberry-commons/wiki/CustomMap