I am using this method in AndEngine to detect when a user taps on the screen,
#Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()) {
if(pSceneTouchEvent.isActionDown()) { //Jump only if the user tapped, not moved his finger or something
taps++;
if(taps == 1){
if(isJumping == false){
final float jumpDuration = 2;
final float startX = player.getY();
final float jumpHeight = 100;
final MoveYModifier moveUpModifier = new MoveYModifier(.1f, startX, startX - jumpHeight);
final MoveYModifier moveDownModifier = new MoveYModifier(.1f, startX - jumpHeight, startX);
final SequenceEntityModifier modifier = new SequenceEntityModifier(moveUpModifier, moveDownModifier);
player.registerEntityModifier(modifier);
isJumping = true;
hipp_jump.play();
return true;
}
}
}
}
return false;
}
Sooo The issue I am having with this is that if the user double-taps the screen, then the sprite jumps twice which moves him out of the position he should return to. Because when it jumps twice the Y changes.
How can I allow the sprite to move only ONCE to each tap, even if the user taps more than once?
The manual solution is to set a delay (record a timestamp of tap), and ignore taps within some timedelta. I suggest using the high-resolution java.lang.System.nanoTime()
Especially capacitive touchscreens are prone to generate multiple taps even unintentionally. It is not handled in Android, and has proven to be a serious problem for our app...
Update: pseudocode sample
private long lastTap=0;
onTap() {
long now = System.nanoTime();
if (now-lastTap < threshold) return;
else lastTap = now;
...
}
Related
I wrote code that is supposed to remove 25 HP (health points) each time a rectangle (created by pressing the m key) intersects another rectangle, the enemy. Currently, the enemy looses 25HP continuously after I've pressed the m key only once until I press the m key again outside of the enemy body.
This is my damage code for the enemy. It turns white when killed, that's why I have df1 etc. there.
void damage() {
//if (callMethod) {
HP -=25;
//callMethod = false;
System.out.println(" " + HP);
//}
if (HP == 0) {
df1 = 200;
df2 = 200;
df3 = 200;
}
}
This is the code for the m input.
void Fight() {
if (keyPressed) {
if (key == 'm'|| key == 'M') {
//villkor, flytta höger, X-led.
fill(255, 0, 0, 63);
noStroke();
rect(xF, yF, wF, hF);
xFF = xF;
yFF = yF;
wFF = wF;
hFF = hF;
}
}
}
Here I have my intersect code:
if (g.intersect(f)) {
f.damage();
}
I would appreciate any help I can get. Apologies for my bad English grammar :)
You can use another boolean variable that tracks whether the action was already taken.
Here's a small example:
boolean alreadyPressed = false;
void draw() {}
void mousePressed() {
if(!alreadyPressed){
background(random(255));
}
alreadyPressed = true;
}
You can then reset the boolean variable whenever you want to be eligible to detect the event again.
I am reading "Learning Java by Building Android Games" and in a Retro Squash Game example I don't know how to implement collision detection for the racket. The movement of the racket uses onTouchEvent. I have tried to implement an if statement but it deosn't get checked until the next touch event- so it doesn't work properly. Please help.
//Event that handles in which direction is the racket moving according to where is the user touching the screen
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
//gets the movement action without the pointers(ACTION_MASK) ??? -U: handles multitouch
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
//what happens if user touches the screen and holds
case MotionEvent.ACTION_DOWN:
//if the screen was touched on the right side of the display than move the racket right
if (motionEvent.getX() >= (screenWidth / 2) && racketPosition.x <= screenWidth) {
racketIsMovingLeft = false;
racketIsMovingRight = true;
} else if (motionEvent.getX() < (screenWidth / 2) && racketPosition.x >= 0) {
racketIsMovingLeft = true;
racketIsMovingRight = false;
} else {
racketIsMovingLeft = false;
racketIsMovingRight = false;
}
break;
//when the user lets go of the screen the racket immediately stops moving
case MotionEvent.ACTION_UP:
racketIsMovingLeft = false;
racketIsMovingRight = false;
break;
}
return true;
}
Ok. I have found the solution. I wasn't looking at the right piece of code - sorry. I have edited the piece which is responsible for changing the racketPoint.x of the racket. Here it is:
public void updateCount() {
//change the racket position according to the movement
if (racketIsMovingRight && (racketPosition.x+racketWidth/2)<=screenWidth) {
racketPosition.x += racketSpeed;
}
if (racketIsMovingLeft && (racketPosition.x-racketWidth/2)>=0) {
racketPosition.x -= racketSpeed;
}
//rest of the code
In my game I have a Bullet class, which is in charge of making a new bullet every time the gun is fired. Upon creation the bullet is added to the Bullets class, which is in charge of keeping track of said bullet, along with the rest of the bullets. I have come across a strange behavior:
After killing an enemy, and then shooting once more, the new bullet has the following traits:
The bullet is the same one (as in the same code id) as the bullet
that killed the enemy. (I.E. if the id was:
com.badlogic.gdx.physics.box2d.Body#fc7157f, then it will be the
exact same id.)
The bullet will appear stuck in place, it's sprite not moving, but according to the game it will have a velocity, but the position remains the same. The only visible movement is when you enable the Box2DDebugRenderer, you can see the body move downwards until hitting the ground at which point he "teleports" back up and slowly falls back down.
The number of stuck bullets are equal to the number of enemies killed.
This is the bullet class:
public class Bullet {
private Body bullet;
public Bullet(final float force, final int bulletDmg, final Weapon weapon,
final World world) {
System.out.println("Position " + weapon.getPosition() + ", Angle: "
+ weapon.getAngle());
final BodyDef bulletDef = new BodyDef();
bulletDef.type = BodyDef.BodyType.DynamicBody;
bulletDef.angle = weapon.getAngle();
bulletDef.position.set(
weapon.getPosition().x
+ (float) (2.5 * MathUtils.cos(weapon.getAngle())),
weapon.getPosition().y
+ (float) (2.5 * MathUtils.sin(weapon.getAngle())));
bulletDef.angle = weapon.getAngle();
PolygonShape bulletShape_1 = new PolygonShape();
bulletShape_1.setAsBox(0.34375f, 0.34375f);
CircleShape bulletShape_2 = new CircleShape();
bulletShape_2.setPosition(new Vector2(0.34375f, 0));
bulletShape_2.setRadius(0.34375f);
final FixtureDef bulletFixture_1 = new FixtureDef();
bulletFixture_1.density = 1f;
bulletFixture_1.shape = bulletShape_1;
bulletFixture_1.friction = 0.25f;
bulletFixture_1.restitution = 0.75f;
final FixtureDef bulletFixture_2 = new FixtureDef();
bulletFixture_2.density = 1;
bulletFixture_2.shape = bulletShape_2;
bulletFixture_2.friction = 0.25f;
bulletFixture_2.restitution = 0.75f;
final Timer creationTimer = new Timer();
creationTimer.scheduleTask(new Task() {
#Override
public void run() {
if (!world.isLocked()) {
System.out.println(bullet);
bullet = world.createBody(bulletDef);
bullet.createFixture(bulletFixture_1);
bullet.createFixture(bulletFixture_2);
System.out.println(bullet);
bullet.applyForceToCenter(
force * MathUtils.cos(weapon.getAngle()), force
* MathUtils.sin(weapon.getAngle()), true);
Sprite sprite = new Sprite(new Texture(
"sprites\\Weapon\\bullet_standard.png"));
sprite.setSize(1.03125f, 0.6875f);
sprite.setOrigin((float) (sprite.getWidth() / 2 - 0.12f),
(float) (sprite.getHeight() / 2));
bullet.setUserData(sprite);
Bullets bullets = Bullets.getInstance(world);
bullets.addBullet(bullet);
bullets.setDmg(bulletDmg);
System.out.println("Create bullet number: " + bullet);
creationTimer.stop();
}
}
}, 0, 1);
creationTimer.start();
}
}
I have been facing this for quite some time now and can't figure out the problem, I would love some assistance with this. Thanks in advance!
Update 1:
I do not reuse any of the bullets created.
This is the code that handles collision with the enemy:
public void onCollision(final Body collidedBody, final String bodyHit,
final int index) {
assert instance != null;
final Timer timer = new Timer();
timer.scheduleTask(new Task() {
#Override
public void run() {
if (!world.isLocked()) {
Circles circles = Circles.getInstance();
if (bodyHit.equalsIgnoreCase("ground")) {
if (bulletGroundCollision.get(index) == 5) {
if (bullets.get(index) != null) {
world.destroyBody(bullets.get(index));
bullets.removeIndex(index);
bulletGroundCollision.removeIndex(index);
}
} else
bulletGroundCollision.set(index,
(bulletGroundCollision.get(index) + 1));
} else if (bodyHit.equalsIgnoreCase("enemy")) {
Circle enemy = circles
.findAccordingToCode(collidedBody);
enemy.damaged(bulletDmg);
System.out.println("Hit at: "
+ bullets.get(index).getPosition());
if (bullets.get(index) != null) {
world.destroyBody(bullets.get(index));
bullets.removeIndex(index);
bulletGroundCollision.removeIndex(index);
}
} else if (bodyHit.equalsIgnoreCase("player")) {
if (bullets.get(index) != null) {
world.destroyBody(bullets.get(index));
bullets.removeIndex(index);
bulletGroundCollision.removeIndex(index);
}
Square square = Square.getInstance(world);
square.damaged(bulletDmg);
}
timer.stop();
}
}
}, 0, 1);
timer.start();
}
The code for the bullet creation is already posted as the bullet class.
bullets - is an Array of bodies that are the bullets.
bulletGroundCollision - is an Array of ints which keeps track of how many times a bullet at i position (i.e. index), hit the ground.
Update 2
I had noticed that after the bullet gets stuck, the collision with the bullet does not happen according to the body, instead it is only when there is a collision with the sprite that a collision is triggered.
Your code is somewhat hard to read. However you need to make sure that after your enemy is dead, you need to update your bullet class again with the update method in your bullet class.
boolean enemyDead;
if(damage<=0)
{
bulletClass.updateBulletLocation();
}
I doesn't look like it to me that you are updating your bullet class after you kill the enemy, and because of this, the bullet stays where it is.
Firstly, i am a complete noob at both C# and Java.
So i have been given this assignment to convert a java applet into C#, i have managed to do everything apart from drawing a rectangle on the screen via drag and drop using mouse events.
Whats supposed to happen is when i click and drag my mouse across the screen a rectangle with no fill and white border should appear. The code i have below is just a white screen with a red cross through it, if i comment out the if(action) statement in the form1_Paint then it works but no rectangle so it must be that code that messing it up.
http://gyazo.com/b2506b8c2ea9b304e34172c42ce98aab <-- what it should look like
http://gyazo.com/a8764ac9f5380f0109623d7a7750ddb6 <-- what it actually looks like
[update]
I have now got a rectangle do display but it happens on the MouseUp event rather than creating it as i am dragging my mouse. The obvious next step was to move it to a different mouse event like mouseMove but then it really messes up and created rectangles constantly as i make it bigger. How can i make it constantly resize the rectangle as i drag my mouse and not keep creating rectangles constantly?
The code
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
g1.DrawImage(bitmap, 0, 0, x1, y1);
}
//added load method
private void Form1_Load(object sender, EventArgs e)//runs functions on load
{
init();
start();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (action)
{
xe = e.X;
ye = e.Y;
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
action = true;
// e.consume();
xs = xe = e.X;
ys = ye = e.Y; // starting point y
Form1_MouseMove(sender, e);
this.Invalidate();
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
using (Graphics g = this.CreateGraphics())
{
Pen pen = new Pen(Color.White);
g.DrawRectangle(pen, xs, ys, Math.Abs(xs - xe), Math.Abs(ys - ye));
}
int z, w;
//e.consume();
//xe = e.X;
//ye = e.Y;
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
this.Invalidate();
//Repaint();
}
The biggest problem in your code is this statement in the Form1_Paint() method:
g1.Dispose();
You should never be disposing the Graphics instance passed to you. It belongs to the framework, not your code. But you should especially never dispose an object that you plan to use later. When you dispose it here, then the Graphics instance isn't valid later on when you try to draw the rectangle.
Note that this is the same as in Java. I hope the original Java code didn't call Graphics.dispose() too!
Some other suggestions:
when creating a new Pen object, add a using statement to ensure the Pen instance you create is disposed properly (you do own that one! :) ). In this case though, you don't need to create a new Pen object...just use the stock Pen provided by .NET. I.e. Pens.White.
you don't appear to be calling Invalidate() in the MouseDown and MouseMove event handlers. You won't get any visual feedback unless you do that, because the Paint event handler won't be called.
Fix the code so it looks like this:
// Little helper method :)
private static void Swap<T>(ref T t1, ref T t2)
{
T temp = t1;
t1 = t2;
t2 = t1;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g1 = e.Graphics;
g1.DrawImage(bitmap, 0, 0, x1, y1);
if (action)
{
//g.setColor(Color.White);
if (xe < xs)
{
Swap(ref xs, ref xe);
}
if (ye < ys)
{
Swap(ref ys, ref ye);
}
g1.DrawRectangle(Pens.White, xs, ys, (xe - xs), (ye - ys));
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
// e.consume();
if (action)
{
xe = e.X;
ye = e.Y;
Invalidate();
//repaint();
}
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
action = true;
// e.consume();
if (action)
{
xs = xe = e.X;
ys = ye = e.Y;
Invalidate();
}
}
I've had a look here, this doesn't seem to fix my problem, the Invalidate();'s make it stutter and when I have it in Form1_Paint it doesn't draw correctly, either draws before straight onto the form, straight after I've zoomed but doesn't actually appear when I'm dragging in my zoom!
I have created three threads in a java program. One is the main program, the others are two classes that extend Thread. The main thread represent a controller for a machine. Another thread is the actuators and the third is the sensors. The controller sets variables in its own class which is read by the actuator thread. The actuator performs certain actions according to the instructions and update its own internal variables. These are in turn read by the sensor thread which reads the actuator variables (representing real world actions) and sets its own internal variables which in turn is read by the controller and we have come full circle. The controller then sets variables according to the new sensed world etc.
The actuators are in a eternal loop sleeping 100 ms in each loop.
The sensors are also in an eternal loop sleeping 20ms per loop.
The system almost works. The main loop will miss the updates from the sensor unless I add a sleep to it as well. My question is now why that is? Even sleep(0) makes the system work. I've placed the statement inside the performJob(Job input) while loop. How does the java main thread without a sleep call act differently than the same thread with?
Concurrency is a fairly new subject to me.
This is the code I am using:
Main:
public class Main {
public static void main(String[] args) {
Controller Press = new Controller();
Press.processUnits(1); // no reset code at the moment, only use 1 at a time
Press.shutdownThreads();
}
}
Controller:
import java.util.LinkedList;
public class Controller extends Thread {
// Constants
static final int STATE_WAITING = 0;
static final int STATE_MOVE_ARMS = 1;
static final int STATE_MOVE_PRESS = 2;
static final int LOADINGARM = 2;
static final int UNLOADINGARM = 1;
static final int NOARM = 0;
static final boolean EXTEND = true;
static final boolean RETRACT = false;
private enum Jobs {
EXTENDRETRACT, ROTATE, MAGNETONOFF, PRESSLOWERRAISE
}
// Class variables
private int currentState;
// Component instructions
private int armChoice = 0;
private boolean bool = false; // on, up, extend / off, down, retract
private boolean[] rotInstr = {false, false}; // {rotate?, left true/right false}
private boolean errorHasOccurred = false;
private boolean pressDir = false;
private Sensors sense = null;
private Actuators act = null;
private LinkedList<Job> queue = null;
// Constructor
public Controller() {
act = new Actuators(0.0f, this);
sense = new Sensors();
act.start();
sense.start();
currentState = STATE_WAITING;
queue = new LinkedList<Job>();
}
// Methods
int[] getArmInstructions() {
int extret = (bool) ? 1 : 0;
int[] ret = {armChoice, extret};
return ret;
}
boolean[] getRotation() {
return rotInstr;
}
int getControllerState() {
return currentState;
}
boolean getPressDirection() {
return pressDir;
}
public boolean processUnits(int nAmount) {
if (run(nAmount)) {
System.out.println("Controller: All units have been processed successfully.");
return true;
} else { // procUnits returning false means something went wrong
System.out.println("Controller: An error has occured. The process cannot complete.");
return false;
}
}
/*
* This is the main run routine. Here the controller analyses its internal state and its sensors
* to determine what is happening. To control the arms and press, it sets variables, these symbolize
* the instructions that are sent to the actuators. The actuators run in a separate thread which constantly
* reads instructions from the controller and act accordingly. The sensors and actuators are dumb, they
* will only do what they are told, and if they malfunction it is up to the controller to detect dangers or
* malfunctions and either abort or correct.
*/
private boolean run(int nUnits) {
/*
Here depending on internal state, different actions will take place. The process uses a queue of jobs
to keep track of what to do, it reads a job, sets the variables and then waits until that job has finished
according to the sensors, it will listen to all the sensors to make sure the correct sequence of events is
taking place. The controller reads the sensor information from the sensor thread which runs on its own
similar to the controller.
In state waiting the controller is waiting for input, when given the thread cues up the appropriate sequence of jobs
and changes its internal state to state move arms
In Move arms, the controller is actively updating its variables as its jobs are performed,
In this state the jobs are, extend, retract and rotate, pickup and drop.
From this state it is possible to go to move press state once certain conditions apply
In Move Press state, the controller through its variables control the press, the arms must be out of the way!
In this state the jobs are press goes up or down. Pressing is taking place at the topmost position, middle position is for drop off
and lower is for pickup. When the press is considered done, the state reverts to move arms,
*/
//PSEUDO CODE:
//This routine being called means that there are units to be processed
//Make sure the controller is not in a blocking state, that is, it shut down previously due to errors
//dangers or malfunctions
//If all ok - ASSUMED SO AS COMPONENTS ARE FAULT FREE IN THIS VERSION
if (!errorHasOccurred) {
//retract arms
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//System.out.println("Jobs added");
//while there are still units to process
for (;nUnits != 0; nUnits--) {
//move the press to lower position, for unloading
currentState = STATE_MOVE_PRESS;
//rotate to pickup area and pickup the metal, also pickup processed
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, EXTEND));
performWork();
//retract and rotate
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//state change, press moves to middle position
currentState = STATE_MOVE_PRESS;
//state change back, put the metal on the press, drop processed and pull arms back
currentState = STATE_MOVE_ARMS;
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, EXTEND));
queue.add(new Job(Jobs.EXTENDRETRACT, LOADINGARM, RETRACT));
queue.add(new Job(Jobs.EXTENDRETRACT, UNLOADINGARM, RETRACT));
performWork();
//state change, press the metal in upper position
currentState = STATE_MOVE_PRESS;
//repeat until done
}
//unload final piece
//move the press to lower position for unload
//rotate and pickup processed piece
//drop it off at unloading and wait for more orders
currentState = STATE_WAITING;
}
return true;
}
private boolean performWork() {
while (!queue.isEmpty()) {
performJob(queue.removeFirst());
}
return true;
}
private boolean performJob(Job input) {
//The purpose of this function is to update the variables and wait until they are completed
// read in the job and check appropriate sensors
boolean[] data = sense.getSensorData(); // LExt, LRet, UlExt, UlRet
printBools(data);
int Instruction = input.Instruction;
boolean skipVars = false;
if (input.Job == Jobs.EXTENDRETRACT) {
if (currentState != STATE_MOVE_ARMS){
System.out.println("Wrong state in performJob. State is "+currentState+" expected "+STATE_MOVE_ARMS);
return false;
}
if ((Instruction == LOADINGARM) && (input.Bool)) skipVars = data[0];
if ((Instruction == LOADINGARM) && (!input.Bool)) skipVars = data[1];
if ((Instruction == UNLOADINGARM) && (input.Bool)) skipVars = data[2];
if ((Instruction == UNLOADINGARM) && (!input.Bool)) skipVars = data[3];
}
if (!skipVars) {
// if sensors not at intended values, update correct variables
System.out.println("Controller: Did not skip vars");
switch (input.Job) {
case EXTENDRETRACT:
armChoice = (Instruction == LOADINGARM) ? LOADINGARM : UNLOADINGARM;
bool = input.Bool;
break;
case ROTATE:
break;
case MAGNETONOFF:
break;
case PRESSLOWERRAISE:
break;
default:
System.out.println("Default called in performJob()");
break;
}
}
// listen to sensors until completed
boolean done = false;
System.out.println("Waiting for sensor data.");
//System.out.print("Instruction is "+Instruction+" and bool is "); if (input.Bool) System.out.print("true\n"); else System.out.print("false\n");
while (!done) {
data = sense.getSensorData();
// REMOVING THIS TRY STATEMENT BREAKS THE PROGRAM
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
System.out.println("Main thread couldn't sleep.");
}
// Check appropriate sensors
if (input.Job == Jobs.EXTENDRETRACT) {
if ((Instruction == LOADINGARM) && (input.Bool)) done = data[0];
if ((Instruction == LOADINGARM) && (!input.Bool)) done = data[1];
if ((Instruction == UNLOADINGARM) && (input.Bool)) done = data[2];
if ((Instruction == UNLOADINGARM) && (!input.Bool)) done = data[3];
}
}
// reset all variables
armChoice = 0;
bool = false;
// when done return
System.out.println("Finished "+input.Job);
return true;
}
public void shutdownThreads() {
sense.shutDown();
act.shutDown();
}
private class Job {
// Class variables
Jobs Job;
int Instruction;
boolean Bool; // used for directions, up/down, left/right, extend/retract
// Constructor
Job(Jobs newJob, int newInstruction, boolean dir) {
Job = newJob;
Instruction = newInstruction;
Bool = dir;
}
}
private void printBools(boolean[] input) {
System.out.println();
for (int i = 0; i < input.length; i++) {
if (input[i]) System.out.print("true "); else System.out.print("false ");
}
System.out.println();
}
}
Actuators:
public class Actuators extends Thread {
// Constants
private final int ARM = 0, ROTATE = 0; // array indexes - which arm, rotate yes/no?
private final int DIR = 1, ROTDIR = 1; // array indexes - which direction ext/ret, rotate direction
private final int EXT = 1;//, RET = 0;
private final double ARM_SPEED = 5.0;
// Class variables
private Controller Owner = null;
private boolean run = true;
// Constructor
Actuators(float nPos, Controller Owner) {
Reality.changeAngle(nPos);
this.Owner = Owner;
}
// Methods
private void rotate(boolean dir) {
float nAngle = dir ? 0.1f : -0.1f;
Reality.changeAngle(nAngle);
}
public void run() {
while (run) {
try {
sleep(100);
} catch (InterruptedException e) {
System.out.println("Actuators couldn't sleep");
}
// read variables in controller
int nState = Owner.getControllerState();
if (nState == Controller.STATE_MOVE_ARMS) {
boolean[] rot = Owner.getRotation();
if (rot[ROTATE]) { // Rotation?
rotate(rot[ROTDIR]);
} else { // or arm extensions
int[] instr = Owner.getArmInstructions();
if (instr[ARM] != Controller.NOARM) { // 0 = no arm movement
//System.out.println("Actuator arm is "+instr[ARM]);
double dir = (instr[DIR] == EXT) ? ARM_SPEED : -ARM_SPEED; // 1 = extend, 0 = retract
Reality.changeArmLength(instr[ARM], dir);
}
}
}
}
}
void shutDown() {
run = false;
}
}
Reality is a class composed of static fields and methods, written to by the actuators and read by sensors.
public class Reality {
// Constants
static private final double EXTEND_LIMIT = 100.0;
static private final double RETRACT_LIMIT = 0.0;
// Variables
private static float ArmsAngle = 0.0f;
// Read by Sensor
static double LoadingArmPos = 0.0;
static double UnloadingArmPos = 0.0;
// Methods
static void changeAngle(float newAngle) {
ArmsAngle = ArmsAngle + newAngle;
if ((ArmsAngle < 0.0f) || (ArmsAngle > 90.0f))
System.out.println("Reality: Unallowed Angle");
}
static void changeArmLength(int nArm, double dPos) { // true = extend, false = retract
switch (nArm) {
case Controller.LOADINGARM:
LoadingArmPos += dPos;
checkArmPos(LoadingArmPos);
break;
case Controller.UNLOADINGARM:
UnloadingArmPos += dPos;
checkArmPos(UnloadingArmPos);
break;
default:
System.out.println("Arm other than 2 (load) or 1 (unload) in changeArmLength in Reality");
break;
}
}
static float senseAngle() {
return ArmsAngle;
}
static private boolean checkArmPos(double dPos) {
// Allowed positions are 100.0 to 0.0
if ((dPos > EXTEND_LIMIT) || (dPos < RETRACT_LIMIT)) {
System.out.println("Arm position impossible in reality. Is "+dPos);
return true;
} else {
return false;
}
}
}
Finally the sensors:
public class Sensors extends Thread {
// Constants
private final double EXTENDED = 100.0;
private final double RETRACTED = 0.0;
private final double MARGIN = 0.1;
// Class Variables
private boolean run = true;
// Read by Controller
private boolean LoadingExtended = true;
private boolean LoadingRetracted = true;
private boolean UnloadingExtended = true;
private boolean UnloadingRetracted = true;
// Constructor
Sensors() {
LoadingExtended = false;
LoadingRetracted = true;
UnloadingExtended = false;
UnloadingRetracted = true;
}
// Methods
boolean senseLoadingExtended() {
return (Math.abs(Reality.LoadingArmPos - EXTENDED) < MARGIN);
}
boolean senseLoadingRetracted() {
return (Math.abs(Reality.LoadingArmPos - RETRACTED) < MARGIN);
}
boolean senseUnloadingExtended() {
return (Math.abs(Reality.UnloadingArmPos - EXTENDED) < MARGIN);
}
boolean senseUnloadingRetracted() {
return (Math.abs(Reality.UnloadingArmPos - RETRACTED) < MARGIN);
}
// called by Controller
boolean[] getSensorData() {
boolean[] ret = {LoadingExtended, LoadingRetracted, UnloadingExtended, UnloadingRetracted};
return ret;
}
// Sensor primary loop
public void run() {
while (run) {
try {
sleep(20);
}
catch (InterruptedException e) {
System.out.println("Sensors couldn't sleep");
}
LoadingExtended = senseLoadingExtended();
LoadingRetracted = senseLoadingRetracted();
UnloadingExtended = senseUnloadingExtended();
UnloadingRetracted = senseUnloadingRetracted();
}
}
void shutDown() {
run = false;
}
}
Not all fields and functions are read in this version. The program is a reworking of a previous single thread application mostly using function calls. I've cleaned up the code a bit for readability. Constructive design remarks are welcome even though it was not the original question. There is something really fishy going on. I am usually not a superstitious coder but I can for example replace the sleep call with a System.out.println() call and the program will work.
Google for 'Producer consumer queue'.
Don't use sleep() for inter-thread comms unless you want latency, inefficiency and lost data. There are much better mechanisms available that avoid sleep() and trying to read valid data directly from some shared/locked object.
If you load up 'comms' objects with commands/requests/data, queue them off to other threads and immediately create another comms object for subsequent communication, your inter-thread comms will be fast and safe, no sleep() latency and no chance of any thread reading data that is stale or being changed by another thread.
What occurred here was most probably a Memory Consistency Error. When the controller class set the internal control variables and then entered the loop waiting for sensors it most likely prevented the Actuators and Sensors classes from properly updating the readings seen to the controller and as such prevented the controller from seeing the correct values. By adding the synchronize statement to all functions which read from another class the problem was solved. I can only speculate that the sleep call had the controller thread enter a synchronized block of some kind which let the other threads' changes to the variables become visible.
Which JVM are you using?
As fast workaround you can set volatile for fields that shared between threads.
Also please look to actors' approach for messaging: http://doc.akka.io/docs/akka/snapshot/java/untyped-actors.html