how to display first two objects in loop of anchor in sceneform ARcCore - augmented-reality

if (frame.getCamera().getTrackingState() == TrackingState.TRACKING && anchorsts && !placed) {
Session session = arFragment.getArSceneView().getSession();
String type = "fwd";
int distance = 0;
int nextPoint = 1;
String[] positions = {"u", "u","r", "r","r", "r", "r", "r", "r", "r"};
if (turnStatus == null){
turnStatus = positions[distance];
Log.i("turnStatus", "pos " + positions[distance]);
}
float[] rotation = {0, 0, 0, 0};
do {
if (positions[distance].equals("u")) {
turnStatus = "u";
placeNav(session, new float[]{dx, dy, dz}, rotation, positions[distance]);
if (!turnStatus.equals(positions[nextPoint])) {
if (positions[nextPoint].equals("r")) {
turnDistance = distance;
}
}
} else if (positions[distance].equals("r")){
turnDistance ++;
turnStatus = "r";
placeNav(session, new float[]{turnDistance, -1.5f, -turnDistance}, rotation, positions[distance]);
if (!turnStatus.equals(positions[nextPoint])) {
if (positions[nextPoint].equals("u")) {
}
}
}
distance++;
nextPoint ++;
} while (distance <9);
placed = true; //to place the arrow just once.
}
private void placeNav(Session session, float[] pos, float[] rotation, String type) {
AnchorNode anchorNode = new AnchorNode(anchor);
currentAnchorNode = anchorNode;
anchorNode.setParent(arFragment.getArSceneView().getScene());
Node arrow = new Node();
arrow.setParent(anchorNode);
if (type.equals("u"))
arrow.setRenderable(andyRenderable);
else if (type.equals("r"))
arrow.setRenderable(andyRenderable);
}
the above code is used to render a loop of renderables into scene. I need to display only first two renderables and display next renderables while user is moving forward. here the positions array isnused to render objects into scene. Please to help me to implement this

Just create the first two renderable in onCreate method. For creating the other renderable, when the person is moving forward, you should check if the new position of the camera is in front of the previous position of the camera.
Vector3 newCameraPosition = getScene().getCamera().getWorldPosition();
Vector3 direction = Vector3.subtract(newCameraPosition, oldCameraPosition);
Quaternion lookRotation = Quaternion.lookRotation(direction, Vector3.up());
double product =
(newCameraPosition.x - oldCameraPosition.x) * direction.x + (newCameraPosition.y - oldCameraPosition.y) * direction.y + (newCameraPosition.z - oldCameraPosition.z) * direction.z;
if (product > 0.0) {
// means camera moved forward
}

Related

How to draw rectangle when form is resized

enter code hereI'm using OpenCv and displaying frames which i get from video file on the imagebox. Now I'm drawing multiple rectangles on the frame and trying to move and delete them. This is working fine. But, when i'm resizing the form...i can't draw,move or delete the rectangles at the correct position as the frame coordinates are not getting changed but only imagebox coordinates are being changed and the frame is fitted into it.Please help me out.
black rectangle is where i have drawn the rectangle after form is resized...red rectangle is where the rectangle is being drawn
private void imageBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
drawRect = true;
RectStartpt = e.Location;
if (count > 0)
{
foreach (Rectangle allRect in Rect_List)
{
rect_count++;
if (allRect.Contains(e.Location))
{
Cursor cursor = Cursors.Cross;
drawRect = false;
RectStartpt = new Point(e.X, e.Y);
rect = allRect;
break;
}
}
}
}this.Invalidate();}
private void imageBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left && e.Button != MouseButtons.Right)
{
return;
}
else if (e.Button == MouseButtons.Left)
{
Point EndPt = new Point(e.X, e.Y);
Size shift = new Size(Math.Abs(RectStartpt.X - EndPt.X), Math.Abs(RectStartpt.Y - EndPt.Y));
if (drawRect == true)
{
rect.Location = new Point(Math.Min(RectStartpt.X, EndPt.X), Math.Min(RectStartpt.Y, EndPt.Y));
rect.Size = shift;
count = 1;
}
else if (drawRect == false)
{
rect.X += e.X - RectStartpt.X;
rect.Y += e.Y - RectStartpt.Y;
RectStartpt = new Point(e.X, e.Y);
}
}
}
private void imageBox1_MouseUp(object sender, MouseEventArgs e)
{
if (frame != null)
{
if (drawRect == true)
{
frame.Draw(rect, new Bgr(Color.Red), 2);
Rect_List.Add(rect);
}
else if (drawRect == false)
{
frame.Draw(rect, new Bgr(Color.Red), 2);
Rect_List.RemoveAt(rect_count - 1);
Rect_List.Add(rect);
if (Timer_enabled == false)
{
frame = captureFrame.QueryFrame().ToImage<Bgr, Byte>();
foreach (Rectangle allRect in Rect_List)
{
frame.Draw(allRect, new Bgr(Color.Red), 2);
}
imageBox1.Image = frame;
imageBox1.Refresh();
rect = new Rectangle();
frame_no++;
}
}
imageBox1.Image = frame;
imageBox1.Refresh();
//rect = new Rectangle();
rect_count = 0;
}
}
private void Form1_Resize(object sender, EventArgs e)
{
formGraphics = null;
formGraphics = imageBox1.CreateGraphics();
frame = frame.Resize(imageBox1.Width, imageBox1.Height, Inter.Linear);
imageBox1.Image = frame;
}

Drawing 2D lines in XNA using rotations

I'm trying to draw a line from the player to a targets asteroid as a "Grapple" hook, i've found some examples for doing this in 2D in xna but my "Position" and "origin" vector2 seems to change depending on who and when they are used. In the case of the lines they appear to draw up and right of the position (roughly 100 pixels) in the opposite direction of the target and rotate about an origin somewhere to the left of the target as the player moves.
here is the player code including the grapple code and target assignment
namespace Sparatius.Sprites
{
public class PlayerSprite : BaseSprite
{
ControlInput controlInput;
Texture2D Grapple;
SpriteFont font;
bool LeftGrapple = false, RightGrapple = false;
int GrappleRange = 300;
Sprites.AsteroidSprite LeftTarget, RightTarget;
public BoundingSphere grappleHitBox
{
get { return new BoundingSphere(new Vector3(Position.X + Origin.X, Position.Y + Origin.Y, 0), GrappleRange); }
}
public float speed
{
get { return Speed; }
}
public PlayerSprite(Vector2 spriteLocal)
:base(spriteLocal)
{
this.Rotation = 0;
this.Speed = 0;
this.FrameCount = new Point(4, 2);
this.ColorTint = Color.White;
this.controlInput = new ControlInput();
}
public void LoadContent(ContentManager content)
{
Texture = content.Load<Texture2D>("Sprites/PinballSpin");
font = content.Load<SpriteFont>("Fonts/Font1");
Grapple = content.Load<Texture2D>("Sprites/Grapple");
FrameSize = new Point((int)Texture.Width / FrameCount.X, (int)Texture.Height / FrameCount.Y);
Origin = new Vector2(FrameSize.X / 2, FrameSize.Y / 2);
Animation = new Animation(Texture, FrameSize);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
controlInput.GetControlStates();
if (controlInput.JustPressed(Keys.W))
Speed += 2;
else if (controlInput.JustPressed(Keys.S))
Speed -= 2;
if (controlInput.IsHeld(Keys.A))
Rotation -= 0.05f;
if (controlInput.IsHeld(Keys.D))
Rotation += 0.05f;
if (LeftTarget != null)
{
LeftTarget.Distance = Vector2.Distance(Position, LeftTarget.Position);
if (LeftTarget.Distance > GrappleRange)
{
LeftTarget.isTarget = false;
LeftTarget = null;
}
if (controlInput.IsHeld(Keys.Q))
{
LeftGrapple = true;
}
else
LeftGrapple = false;
}
if (RightTarget != null)
{
RightTarget.Distance = Vector2.Distance(Position, RightTarget.Position);
if (RightTarget.Distance > GrappleRange)
{
RightTarget.isTarget = false;
RightTarget = null;
}
if (controlInput.IsHeld(Keys.E))
{
RightGrapple = true;
}
else
RightGrapple = false;
}
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (LeftGrapple)
{
float leftRotation = (float)Math.Atan2(LeftTarget.Position.Y - Position.Y, LeftTarget.Position.X - Position.X);
//spriteBatch.Draw(Texture, Position, null, ColorTint, leftRotation, Position, 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(Grapple,
new Rectangle((int)Position.X, (int)Position.Y, 2, (int)LeftTarget.Distance),
null, Color.Blue, leftRotation, Position, SpriteEffects.None, 0f);
}
if (RightGrapple)
{
float rightRotation = (float)Math.Atan2(RightTarget.Position.Y - Position.Y, RightTarget.Position.X - Position.X);
//spriteBatch.Draw(Texture, Position, null, ColorTint, rightRotation, Position, 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(Grapple,
new Rectangle((int)Position.X, (int)Position.Y, 2, (int)RightTarget.Distance),
null, Color.Blue, rightRotation, Position, SpriteEffects.None, 0f);
}
spriteBatch.DrawString(font, "Player Rotation: " + Rotation, Position, Color.Red);
spriteBatch.DrawString(font, "Player RoationDegree: " + (int)MathHelper.ToDegrees(Rotation), origin, Color.Blue);
}
public void GrappleCheck(AsteroidSprite target)
{
float targetTragectory = (float)Math.Atan2(Position.Y - target.Position.Y, Position.X - target.Position.X);
if ((targetTragectory < (rotation - (float)MathHelper.PiOver4)) && ((targetTragectory > (rotation - (float)MathHelper.Pi + (float)MathHelper.PiOver4))))
{
target.Distance = Vector2.Distance(Position, target.Position);
if (LeftTarget != null)
{
if (LeftTarget.Distance > target.Distance)
{
LeftTarget.isTarget = false;
LeftTarget = target;
LeftTarget.isTarget = true;
}
}
else
{
LeftTarget = target;
LeftTarget.isTarget = true;
}
}
if ((targetTragectory > (rotation + (float)MathHelper.PiOver4)) && ((targetTragectory < (rotation + (float)MathHelper.Pi - (float)MathHelper.PiOver4))))
{
target.Distance = Vector2.Distance(Position, target.Position);
if (RightTarget != null)
{
if (RightTarget.Distance > target.Distance)
{
RightTarget.isTarget = false;
RightTarget = target;
RightTarget.isTarget = true;
}
}
else
{
RightTarget = target;
RightTarget.isTarget = true;
}
}
}
}
}
any idea whats going wrong? cheers
public static void DrawLine(SpriteBatch spriteBatch, Vector2 begin, Vector2 end, Color color, int width = 1)
{
Rectangle r = new Rectangle((int)begin.X, (int)begin.Y, (int)(end - begin).Length()+width, width);
Vector2 v = Vector2.Normalize(begin - end);
float angle = (float)Math.Acos(Vector2.Dot(v, -Vector2.UnitX));
if (begin.Y > end.Y) angle = MathHelper.TwoPi - angle;
spriteBatch.Draw(Pixel, r, null, color, angle, Vector2.Zero, SpriteEffects.None, 0);
}
Pixel is just a 1x1 sprite
You can also use the this keyword to make a handy extension method.

Processing with tuio

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"

XNA Windows Phone 7 Sprite movement

I'm working on a Windows phone game and I'm having difficulty with the sprite movement.
What I want to do is make the sprite gradually move to the position that is touched on screen, when there is only one quick touch and release.
At the minute all I can do is either make the sprite jump instantly to the touch location or move along to the touch location when the touch is held down.
Code for jumping to touch location:
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed)
|| (tl.State == TouchLocationState.Moved))
{
Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);
if (position != newPos)
{
while (position.X < newPos.X)
{
position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;
}
}
}
}
Code to gradually move along while touch is held:
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed)
|| (tl.State == TouchLocationState.Moved))
{
Vector2 newPos = new Vector2(tl.Position.X,tl.Position.Y);
if (position != newPos)
{
position.X += (float)theGameTime.ElapsedGameTime.Milliseconds / 10.0f * spriteDirectionRight;
}
}
}
These are in the Update() method of the Sprite class.
Something like this...sorry I didn't run it through a compiler so there may be some syntax errors. Declare these as fields in the class:
Vector2 newPos;
bool moving = false;
then in the Update method:
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if ((tl.State == TouchLocationState.Pressed)
|| (tl.State == TouchLocationState.Moved)
|| (tl.State == TouchLocationState.Released))
{
newPos = new Vector2(tl.Position.X, tl.Position.Y);
moving = true;
}
}
if (moving && newPos != position)
{
Vector2 delta = newPos - position;
Vector2 norm = delta;
norm.Normalize();
Vector2 distanceToMove = norm * ((float)gameTime.ElapsedGameTime.TotalMilliseconds * .5f);
if (distanceToMove.LengthSquared() > delta.LengthSquared())
{
position = newPos;
moving = false;
}
else
{
position += distanceToMove;
}
}

How to show more than one location in Blackberry MapField?

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

Resources