I've got a project that is built on the serverless Twilio Voice JavaScript quickstart. Here's a link to the quickstart.
https://www.twilio.com/docs/voice/sdks/javascript/get-started#information
Below is the chunk of code where it allows the user to select an audio output device. Is it possible to select more than one audio output device, so my users can hear their phones ring through their speakers AND their headsets at the same time?
function updateDevices(selectEl, selectedDevices) {
selectEl.innerHTML = '';
device.audio.availableOutputDevices.forEach(function (device, id) {
let isActive = selectedDevices.size === 0 && id === 'default';
selectedDevices.forEach(function (device) {
if (device.deviceId === id) {
isActive = true;
}
});
const option = document.createElement('option');
option.label = device.label;
option.setAttribute('data-id', id);
if (isActive) {
option.setAttribute('selected', 'selected');
}
selectEl.appendChild(option);
});
}
function updateAllAudioDevices() {
if (device) {
updateDevices(speakerDevices, device.audio.speakerDevices.get());
updateDevices(ringtoneDevices, device.audio.ringtoneDevices.get());
}
}
async function getAudioDevices() {
await navigator.mediaDevices.getUserMedia({ audio: true });
updateAllAudioDevices.bind(device);
}
function updateOutputDevice() {
const selectedDevices = Array.from(speakerDevices.children)
.filter((node) => node.selected)
.map((node) => node.getAttribute('data-id'));
device.audio.speakerDevices.set(selectedDevices);
}
function updateRingtoneDevice() {
const selectedDevices = Array.from(ringtoneDevices.children)
.filter((node) => node.selected)
.map((node) => node.getAttribute('data-id'));
device.audio.ringtoneDevices.set(selectedDevices);
}
function bindVolumeIndicators(call) {
call.on('volume', function (inputVolume, outputVolume) {
let inputColor = 'red';
if (inputVolume < 0.5) {
inputColor = 'green';
} else if (inputVolume < 0.75) {
inputColor = 'yellow';
}
inputVolumeBar.style.width = `${Math.floor(inputVolume * 300)}px`;
inputVolumeBar.style.background = inputColor;
let outputColor = 'red';
if (outputVolume < 0.5) {
outputColor = 'green';
} else if (outputVolume < 0.75) {
outputColor = 'yellow';
}
outputVolumeBar.style.width = `${Math.floor(outputVolume * 300)}px`;
outputVolumeBar.style.background = outputColor;
});
}
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;
}
I'm creating a game where you as the player is holding a baseball bat and when you click the button you swing your bat. When you swing your bat you hit the enemy the enemy goes flying off in the opposite direction of where you hit them like a golf ball. I have done the moving and attacking function working but how can I register the hittest so it hits the enemy when facing towards it and the enemy going back. This is what I done so far:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Player extends MovieClip
{
var walkSpeed:Number = 4;
var walkRight:Boolean = false;
var walkLeft:Boolean = false;
var walkUp:Boolean = false;
var walkDown:Boolean = false;
var attacking:Boolean = false;
public function Player()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN , walk);
addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_UP, stopWalk);
stage.addEventListener(MouseEvent.CLICK, attack);
}
function walk(event:KeyboardEvent)
{
if (event.keyCode == 68)
{
walkRight = true;
}
if (event.keyCode == 87)
{
walkUp = true;
}
if (event.keyCode == 65)
{
walkLeft = true;
}
if (event.keyCode == 83)
{
walkDown = true;
}
}
function Update(event:Event)
{
if (attacking == true)
{
walkRight = false;
walkLeft = false;
walkUp = false;
walkDown = false;
}
else if (attacking == false)
{
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
if (walkRight == true)
{
x += walkSpeed;
gotoAndStop('walk');
}
if (walkUp == true)
{
y -= walkSpeed;
gotoAndStop('walk');
}
if (walkLeft == true)
{
x -= walkSpeed;
gotoAndStop('walk');
}
if (walkDown == true)
{
y += walkSpeed;
gotoAndStop('walk');
}
}
}
function stopWalk(event:KeyboardEvent)
{
if (attacking == false)
{
if (event.keyCode == 68)
{
event.keyCode = 0;
walkRight = false;
gotoAndStop('stance');
}
if (event.keyCode == 87)
{
event.keyCode = 0;
walkUp = false;
gotoAndStop('stance');
}
if (event.keyCode == 65)
{
event.keyCode = 0;
walkLeft = false;
gotoAndStop('stance');
}
if (event.keyCode == 83)
{
event.keyCode = 0;
walkDown = false;
gotoAndStop('stance');
}
}
}
function attack(event:MouseEvent)
{
if (attacking == false)
{
attacking = true;
gotoAndStop('attack');
}
}
}
}
When the character's direction changes, change a variable depending on the way they are now facing, for example; direction = 0 when they are facing down, 1 when they are facing right, etc. Then use this and the enemy's position to work out whether or not the enemy has been hit. For making the enemy fly back, you would get the character's direction to work out which way they would fly back. I would give some example code to help explain, but I'm on my tablet.
Making a touch based platform game based in actionscript 3 using Gary Rosenzweig's game as a basis, all was going well until today, I've been trying to swap out floor objects etc without changing much of the actionscript at all and I have the following error.
ArgumentError: Error #2109: Frame label jump not found in scene jump.
at flash.display::MovieClip/gotoAndStop()
at PlatformGame/moveCharacter()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:418]
at PlatformGame/moveEnemies()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:314]
at PlatformGame/gameLoop()[C:\Users\Michael\Desktop\platformGame\PlatformGame.as:303]
This also seems to cause problems with collision detection.
The code is as follows. (not i have not changed the scene or label names from the originals but it still shows the error).
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class PlatformGame extends MovieClip {
// movement constants
static const gravity:Number = .004;
// screen constants
static const edgeDistance:Number = 100;
public var rightButton:SimpleButton;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String = "start";
private var playerLives:int;
private var lastTime:Number = 0;
// start game
public function startPlatformGame() {
playerObjects = new Array();
gameScore = 0;
gameMode = "play";
playerLives = 3;
}
// start level
public function startGameLevel() {
// create characters
createHero();
addEnemies();
// examine level and note all objects
examineLevel();
// add listeners
this.addEventListener(Event.ENTER_FRAME,gameLoop);
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchRight);
gamelevel["rButton"].addEventListener(TouchEvent.TOUCH_END,touchRightReleased);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_BEGIN,touchLeft);
gamelevel["lButton"].addEventListener(TouchEvent.TOUCH_END,touchLeftReleased);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_BEGIN,jump);
gamelevel["jButton"].addEventListener(TouchEvent.TOUCH_END,jumpReleased);
trace("hi"+gamelevel["rButton"]);
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHarder() {
// create characters
createHero();
addHardEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// start level
public function startGameLevelHardest() {
// create characters
createHero();
addHardestEnemies();
// examine level and note all objects
examineLevel();
// set game state
gameMode = "play";
addScore(0);
showLives();
}
// creates the hero object and sets all properties
public function createHero() {
hero = new Object();
hero.mc = gamelevel.hero;
hero.dx = 0.0;
hero.dy = 0.0;
hero.inAir = false;
hero.direction = 0;
hero.animstate = "stand";
hero.walkAnimation = new Array(2,3,4,5,6,7,8);
hero.animstep = 0;
hero.jump = false;
hero.moveLeft = false;
hero.moveRight = false;
hero.jumpSpeed = .8;
hero.walkSpeed = .15;
hero.width = 15.0;
hero.height = 35.0;
hero.startx = hero.mc.x;
hero.starty = hero.mc.y;
}
// finds all enemies in the level and creates an object for each
public function addEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .15;
enemy.width = 56.0;
enemy.height = 80.0;
enemies.push(enemy);
i++;
}
}
// finds all enemies in the level and creates an object for each
public function addHardestEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .25;
enemy.width = 40.0;
enemy.height = 40.0;
enemies.push(enemy);
i++;
}
}
// look at all level children and note walls, floors and items
public function examineLevel() {
fixedObjects = new Array();
otherObjects = new Array();
for(var i:int=0;i<this.gamelevel.numChildren;i++) {
var mc = this.gamelevel.getChildAt(i);
// add floors and walls to fixedObjects
if ((mc is Floor) || (mc is Wall) || (mc is ground1) || (mc is wall1) || (mc is ledge1) || (mc is ledge2) || (mc is rock) ||(mc is rocktip)) {
var floorObject:Object = new Object();
floorObject.mc = mc;
floorObject.leftside = mc.x;
floorObject.rightside = mc.x+mc.width;
floorObject.topside = mc.y;
floorObject.bottomside = mc.y+mc.height;
fixedObjects.push(floorObject);
// add treasure, key and door to otherOjects
} else if ((mc is Treasure) || (mc is Key) || (mc is Door) || (mc is Chest)) {
otherObjects.push(mc);
}
}
}
// note key presses, set hero properties
public function touchRight(event:TouchEvent) {
trace("touchRight");
hero.moveRight = true;
}
public function touchRightReleased(event:TouchEvent) {
hero.moveRight = false;
}
public function touchLeft(event:TouchEvent) {
hero.moveLeft = true;
}
public function touchLeftReleased(event:TouchEvent) {
hero.moveLeft = false;
}
public function jump(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = true;
}
}
public function jumpReleased(event:TouchEvent) {
if (!hero.inAir) {
hero.jump = false;
}
}
// note key presses, set hero properties
//public function keyDownFunction(event:KeyboardEvent) {
//if (gameMode != "play") return; // don't move until in play mode
//if (event.keyCode == 37) {
//hero.moveLeft = true;
//} else if (event.keyCode == 39) {
//hero.moveRight = true;
//} else if (event.keyCode == 32) {
//if (!hero.inAir) {
//hero.jump = true;
//}
//}
//}
//public function keyUpFunction(event:KeyboardEvent) {
//if (event.keyCode == 37) {
//hero.moveLeft = false;
//} else if (event.keyCode == 39) {
//hero.moveRight = false;
//}
//}
// perform all game tasks
public function gameLoop(event:Event) {
// get time differentce
if (lastTime == 0) lastTime = getTimer();
var timeDiff:int = getTimer()-lastTime;
lastTime += timeDiff;
// only perform tasks if in play mode
if (gameMode == "play") {
moveCharacter(hero,timeDiff);
moveEnemies(timeDiff);
checkCollisions();
scrollWithHero();
}
}
// loop through all enemies and move them
public function moveEnemies(timeDiff:int) {
for(var i:int=0;i<enemies.length;i++) {
// move
moveCharacter(enemies[i],timeDiff);
// if hit a wall, turn around
if (enemies[i].hitWallRight) {
enemies[i].moveLeft = true;
enemies[i].moveRight = false;
} else if (enemies[i].hitWallLeft) {
enemies[i].moveLeft = false;
enemies[i].moveRight = true;
}
}
}
// primary function for character movement
public function moveCharacter(char:Object,timeDiff:Number) {
if (timeDiff < 1) return;
// assume character pulled down by gravity
var verticalChange:Number = char.dy*timeDiff + timeDiff*gravity;
if (verticalChange > 15.0) verticalChange = 15.0;
char.dy += timeDiff*gravity;
// react to changes from key presses
var horizontalChange = 0;
var newAnimState:String = "stand";
var newDirection:int = char.direction;
if (char.moveLeft) {
// walk left
horizontalChange = -char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = -1;
} else if (char.moveRight) {
// walk right
horizontalChange = char.walkSpeed*timeDiff;
newAnimState = "walk";
newDirection = 1;
}
if (char.jump) {
// start jump
char.jump = false;
char.dy = -char.jumpSpeed;
verticalChange = -char.jumpSpeed;
newAnimState = "jump";
}
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for(var i:int=0;i<fixedObjects.length;i++) {
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside)) {
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside)) {
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
}
}
}
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for(i=0;i<fixedObjects.length;i++) {
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside)) {
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside)) {
newX = fixedObjects[i].rightside+char.width/2;
char.hitWallLeft = true;
break;
}
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside)) {
newX = fixedObjects[i].leftside-char.width/2;
char.hitWallRight = true;
break;
}
}
}
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir) {
newAnimState = "";
}
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk") {
char.animstep += timeDiff/60;
if (char.animstep > char.walkAnimation.length) {
char.animstep = 0;
}
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
} else {
char.mc.gotoAndStop(char.animstate);
}
// changed directions
if (newDirection != char.direction) {
char.direction = newDirection;
char.mc.scaleX = char.direction*1.35;
}
}
// scroll to the right or left if needed
public function scrollWithHero() {
var stagePosition:Number = gamelevel.x+hero.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge) {
gamelevel.x -= (stagePosition-rightEdge);
gamelevel["rButton"].x += (stagePosition-rightEdge);
gamelevel["lButton"].x += (stagePosition-rightEdge);
gamelevel["jButton"].x += (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth)) gamelevel.x = -(gamelevel.width-stage.stageWidth);
}
if (stagePosition < leftEdge) {
gamelevel.x += (leftEdge-stagePosition);
gamelevel["rButton"].x -= (leftEdge-stagePosition);
gamelevel["lButton"].x -= (leftEdge-stagePosition);
gamelevel["jButton"].x -= (leftEdge-stagePosition);
if (gamelevel.x > 0) gamelevel.x = 0;
}
}
// check collisions with enemies, items
public function checkCollisions() {
// enemies
for(var i:int=enemies.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(enemies[i].mc)) {
// is the hero jumping down onto the enemy?
if (hero.inAir && (hero.dy > 0)) {
enemyDie(i);
} else {
heroDie();
}
}
}
// items
for(i=otherObjects.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(otherObjects[i])) {
getObject(i);
}
}
}
// remove enemy
public function enemyDie(enemyNum:int) {
var pb:PointBurst = new PointBurst(gamelevel,"Got Em!",enemies[enemyNum].mc.x,enemies[enemyNum].mc.y-20);
gamelevel.removeChild(enemies[enemyNum].mc);
enemies.splice(enemyNum,1);
}
// enemy got player
public function heroDie() {
// show dialog box
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
if (playerLives == 0) {
gameMode = "gameover";
dialog.message.text = "Game Over!";
} else {
gameMode = "dead";
dialog.message.text = "He Got You!";
playerLives--;
}
hero.mc.gotoAndPlay("die");
}
// player collides with objects
public function getObject(objectNum:int) {
// award points for treasure
if (otherObjects[objectNum] is Treasure) {
var pb:PointBurst = new PointBurst(gamelevel,100,otherObjects[objectNum].x,otherObjects[objectNum].y);
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
addScore(100);
// got the key, add to inventory
} else if (otherObjects[objectNum] is Key) {
pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
// hit the door, end level if hero has the key
} else if (otherObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return;
if (otherObjects[objectNum].currentFrame == 1) {
otherObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
// got the chest, game won
} else if (otherObjects[objectNum] is Chest) {
otherObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
// add points to score
public function addScore(numPoints:int) {
gameScore += numPoints;
scoreDisplay.text = String(gameScore);
}
// update player lives
public function showLives() {
livesDisplay.text = String(playerLives);
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
// game over, bring up dialog
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
// dialog button clicked
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
showLives();
hero.mc.x = hero.startx;
hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
}
}
}
The error is with the following line and is occurring because the referenced MovieClip does not have a frame labelled "jump":
char.mc.gotoAndStop(char.animstate);
My guess is that you made a change to the MovieClip which contains your character and, in doing so, removed the label which the code above references.