Here is my navigationMovement():
protected boolean navigationMovement(int dx, int dy, int status, int time) {
int focusIndex = getFieldWithFocusIndex();
while (dy > 0) {
if (focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dy--;
}
}
}
while (dy < 0) {
if (focusIndex < 0) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dy++;
}
}
}
while (dx > 0) {
focusIndex++;
if (focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx--;
}
}
}
while (dx < 0) {
focusIndex--;
if (focusIndex < 0) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx++;
}
}
}
return true;
}
This only allows the track wheel to scroll left and right, but I want up, down, left and right.
my layout is this.
It is a 3 rows x 4 columns.
This code is checking getField(0->10), that's why it cannot from 0 to 4.
I want it to be movable in all directions. How to implement that?
Updated
protected void sublayout(int width, int height) {
int y = 0;
Field[] fields = new Field[columnWidths.length];
int currentColumn = 0;
int rowHeight = 0;
for (int i = 0; i < getFieldCount(); i++) {
fields[currentColumn] = getField(i);
fields[currentColumn]
.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
final int focusIndex = getFieldWithFocusIndex();
if (focusIndex == position) {
Main.getUiApplication().popScreen(
mainscreen);
} else {
Main.getUiApplication().popScreen(
mainscreen);
Main.getUiApplication().pushScreen(
new Custom_LoadingScreen(1));
Main.getUiApplication().invokeLater(
new Runnable() {
public void run() {
if (focusIndex == 0)
Main.getUiApplication()
.pushScreen(
new Main_AllLatestNews());
else
Main.getUiApplication()
.pushScreen(
new Main_ParticularCategoryAllNews(
catnewsid[focusIndex],
focusIndex,
cattitle[focusIndex]));
}
}, 1 * 1000, false);
}
}
});
layoutChild(fields[currentColumn], columnWidths[currentColumn],
height - y);
if (fields[currentColumn].getHeight() > rowHeight) {
rowHeight = fields[currentColumn].getHeight() + 10;
}
currentColumn++;
if ((currentColumn == columnWidths.length)
|| (i == (getFieldCount() - 1))) {
int x = 0;
if (this.allRowHeight >= 0) {
rowHeight = this.allRowHeight;
}
for (int c = 0; c < currentColumn; c++) {
long fieldStyle = fields[c].getStyle();
int fieldXOffset = 0;
long fieldHalign = fieldStyle & Field.FIELD_HALIGN_MASK;
if (fieldHalign == Field.FIELD_RIGHT) {
fieldXOffset = columnWidths[c]
- fields[c].getWidth();
} else if (fieldHalign == Field.FIELD_HCENTER) {
fieldXOffset = (columnWidths[c] - fields[c]
.getWidth()) / 2;
}
int fieldYOffset = 0;
long fieldValign = fieldStyle & Field.FIELD_VALIGN_MASK;
if (fieldValign == Field.FIELD_BOTTOM) {
fieldYOffset = rowHeight - fields[c].getHeight();
} else if (fieldValign == Field.FIELD_VCENTER) {
fieldYOffset = (rowHeight - fields[c].getHeight()) / 2;
}
setPositionChild(fields[c], x + fieldXOffset, y
+ fieldYOffset);
x += columnWidths[c];
}
currentColumn = 0;
y += rowHeight;
}
if (y >= height) {
break;
}
}
int totalWidth = 0;
for (int i = 0; i < columnWidths.length; i++) {
totalWidth += columnWidths[i];
}
if (position > -1) {
Field f = getField(position);
f.setFocus();
}
setExtent(totalWidth, Math.min(y, height));
}
}
The issue with your code that you treat dx and dy in the same way. You need to calculate next previous index differently depends on if it's horizontal scroll or vertical.
Btw, what manager do you use? FlowFieldManager? Because I think it's should work as expected in default navigationMovement implementation.
navigationMovement default will provide focus on all focusable components.
It only matters what layout you have used & how did you arrange these managers. You have row, column wise structure, so if you used horizonal manager for a row, it's elements will get focus & after completing all elements, focus will be down to the second horizontal manager.
I just find the solution which is each move +/- column size
while (dy > 0) {
if (focusIndex + columnwidth.length >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex + columnwidth.length);
if (f.isFocusable()) {
f.setFocus();
dy--;
}
}
}
while (dy < 0) {
if (focusIndex - columnwidth.length < 0) {
return false;
} else {
Field f = getField(focusIndex - columnwidth.length);
if (f.isFocusable()) {
f.setFocus();
dy++;
}
}
}
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>
can anyone help me in my code. I am getting WA and m not able to rectify it plzzz
my code http://ideone.com/DkrwIg
problem link : http://www.spoj.com/problems/BRCKTS/
i am a bit doubtful in my modification function.
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
char str[40010];
struct node
{
int sum;
int minsum;
}tree[1000005];
void build(int id,int l,int r)
{
if(r-l<2)
{
if(str[l] == '(')
{
tree[id].sum = 1;
tree[id].minsum = 1;
}
else
{
tree[id].sum = -1;
tree[id].minsum = -1;
}
return;
}
int mid = (r+l)/2;
build(id*2,l,mid);
build(id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
void modify(int index,int id,int l,int r)
{
if(r-l<2)
{
tree[id].sum = tree[id].minsum = -tree[id].sum;
return;
}
int mid = (r+l)/2;
if(index<mid)
modify(index,id*2,l,mid);
else
modify(index,id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
int main()
{
int n,k;
int val;
int h = 1;
for(int h=1;h<=10;h++)
{
scanf("%d",&n);
scanf("%s",str);
build(1,0,n);
//cout<<"Test "<<h<<" :"<<endl;
printf("Test %d:\n",h);
//cin>>k;
scanf("%d",&k);
while(k--)
{
cin>>val;
if(!val)
{
if(tree[1].sum == 0 && tree[1].minsum == 0)
{
//cout<<"YES"<<endl;
printf("YES\n");
}
else
{
//cout<<"NO"<<endl;
printf("NO\n");
}
//cout<<tree[1].sum<<"------------"<<tree[1].minsum<<endl;
}
else
{
modify(val-1,1,0,n);
}
}
}
return 0;
}
Currently I'm working on a project recreating a mario level, my issue is that when I do not hard code the bottomLimit (the floor, currently set to 400) Mario will eventually just fall through.
Another thing I can't quite figure out is how I can move my invisible block that creates the floor boundary to accomodate the flooring. The level chosen is the Fortress level of Super Mario Brothers 3, if that helps picture what I'm trying to do with it.
There are a couple .as files to my code, I will put my troublesome file in along with my collision code.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.media.Sound;
public class FortressMap extends MovieClip
{
private var _mario:SmallMario;
private var vx:Number = 0;
private var vy:Number = 0;
private var _ceiling:Array = new Array();
private var _floor:Array = new Array();
public const accy:Number = 0.20;
public const termv:Number = 15;
public var onGround:Boolean;
public var bottomLimit:Number;
public function FortressMap()
{
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
_mario = new SmallMario();
addChild(_mario);
_mario.x = 50;
_mario.y = 400;
//Creating the blocks for the floor
createFloor(16, 416);
//Creating the blocks for the ceiling
createCeiling(16, 352);
}
private function createFloor(xPos:Number, yPos:Number):void
{
var floor:Floor = new Floor();
addChild(floor);
floor.x = xPos;
floor.y = yPos;
floor.height = 16;
_floor.push(floor);
floor.visible = false;
}
private function createCeiling(xPos:Number, yPos:Number):void
{
var ceiling:Ceiling = new Ceiling();
addChild(ceiling);
ceiling.x = xPos;
ceiling.y = yPos;
ceiling.height = 16;
_ceiling.push(ceiling);
ceiling.visible = false;
}
private function addedToStageHandler(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.ENTER_FRAME, frameHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removeStageHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
}
private function frameHandler(event:Event):void
{
_mario.x += vx;
_mario.y += vy;
if (_mario.x < 16)
{
_mario.x = 16;
}
vy += accy;
for (var i:int = 0; i < _ceiling.length; ++i)
{
Collision.block(_mario, _ceiling[i]);
}
for (var j:int = 0; j < _floor.length; ++j)
{
Collision.block(_mario, _floor[j]);
}
bottomLimit = 400;
if(_mario.y >= bottomLimit)
{
_mario.y = bottomLimit;
vy = 0;
onGround = true;
}
else
{
onGround = false;
}
}
private function keyDownHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT)
{
vx = -5;
return;
}
if (event.keyCode == Keyboard.RIGHT)
{
vx = 5;
return;
}
if (event.keyCode == Keyboard.UP)
{
if(onGround == true)
{
vy = -5;
trace("My people need me!");
}
return;
}
if (event.keyCode == Keyboard.DOWN)
{
//vy = 5;
return;
}
}
private function keyUpHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
vx = 0;
return;
}
if (event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
//vy = 0;
return;
}
}
private function removeStageHandler(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, frameHandler);
removeEventListener(Event.REMOVED_FROM_STAGE, removeStageHandler);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
}
}
package
{
import flash.display.Sprite;
public class Collision
{
static public var collisionSide:String = "";
public function Collision()
{
}
static public function block(r1:Sprite, r2:Sprite):Boolean
{
var isBlocked:Boolean;
//Calculate the distance vector
var vx:Number
= (r1.x + (r1.width / 2))
- (r2.x + (r2.width / 2));
var vy:Number
= (r1.y + (r1.height / 2))
- (r2.y + (r2.height / 2));
//Check whether vx
//is less than the combined half widths
if(Math.abs(vx) < r1.width / 2 + r2.width / 2)
{
//A collision might be occurring! Check
//whether vy is less than the combined half heights
if(Math.abs(vy) < r1.height / 2 + r2.height / 2)
{
//A collision has ocurred! This is good!
//Find out the size of the overlap on both the X and Y axes
var overlap_X:Number
= r1.width / 2
+ r2.width / 2
- Math.abs(vx);
var overlap_Y:Number
= r1.height / 2
+ r2.height / 2
- Math.abs(vy);
//The collision has occurred on the axis with the
//*smallest* amount of overlap. Let's figure out which
//axis that is
if(overlap_X >= overlap_Y)
{
//The collision is happening on the X axis
//But on which side? _v0's vy can tell us
if(vy > 0)
{
collisionSide = "Top";
//Move the rectangle out of the collision
r1.y = r1.y + overlap_Y;
//r1 is being blocked
isBlocked = true;
}
else
{
collisionSide = "Bottom";
//Move the rectangle out of the collision
r1.y = r1.y - overlap_Y;
//r1 is being blocked
isBlocked = true;
}
}
else
{
//The collision is happening on the Y axis
//But on which side? _v0's vx can tell us
if(vx > 0)
{
collisionSide = "Left";
//Move the rectangle out of the collision
r1.x = r1.x + overlap_X;
//r1 is being blocked
isBlocked = true;
}
else
{
collisionSide = "Right";
//Move the rectangle out of the collision
r1.x = r1.x - overlap_X;
//r1 is being blocked
isBlocked = true;
}
}
}
else
{
//No collision
collisionSide = "No collision";
//r1 is not being blocked
isBlocked = false;
}
}
else
{
//No collision
collisionSide = "No collision";
//r1 is not being blocked
isBlocked = false;
}
return isBlocked;
}
}
}
I think what you want to do is to set the bottomlimit, but not hardcode the number 400, correct?
I would do change your createFloor method:
private function createFloor(xPos:Number, yPos:Number):void
{
var floor:Floor = new Floor();
addChild(floor);
floor.x = xPos;
floor.y = yPos;
floor.height = 16;
_floor.push(floor);
floor.visible = false;
// set bottom limit here
bottomLimit = yPos;
}
... then you wouldnt need to set it to 400.
However, another option is to change your if statement:
if(_mario.y >= Floor(_floor[0]).y)
{
_mario.y = Floor(_floor[0]).y;
vy = 0;
onGround = true;
}
else
{
onGround = false;
}
... and then you can get rid of the bottomLimit variable completely
(assuming I understood your code, and that the floor tiles are always going to be at the bottomLimit)
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"
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;
}
}
}