actionscript circle entire drawing moves why? - actionscript

package {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class helloworld extends Sprite {
public static var x:int = 0;
public static var y:int = 0;
public function helloworld() {
graphics.lineStyle(1, 0, 1);
stage.focus = this;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function onKeyDown(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.DOWN)
{
y++;
graphics.moveTo(x,y);
graphics.drawCircle(x, y, 10);
}
if (event.keyCode == Keyboard.RIGHT)
{
x++;
graphics.moveTo(x,y);
graphics.drawCircle(x, y, 10);
}
}
}
The circles that are drawn first also move. How can I stop it from doing that?

You think you're using your public static x & y values, but actually you're using the Sprite's built in x and y properties which control its location on the stage. When you use y++ and x++ it moves the entire sprite down/right.
You should either make sure you're always calling helloworld.x && helloworld.y (bad idea, easy to forget).
OR
You should not use variables named x and y. Try: circleX and circleY or something that is more descriptive of what you're using it for.

Related

mystery Error #1063: Argument count mismatch

So I'm getting a "Error #1063: Argument count mismatch" error. The weird thing is that it isn't keeping the game from running, but I would like to know why I'm even getting an error in the first place. The full error is:
ArgumentError: Error #1063: Argument count mismatch on Hock(). Expected 3, got 0.
at flash.display::Sprite/constructChildren()
at flash.display::Sprite()
at flash.display::MovieClip()
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
at Main/addPlayscreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:17]
at Main()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\Main.as:13]
at runtime::ContentPlayer/loadInitialContent()
at runtime::ContentPlayer/playRawContent()
at runtime::ContentPlayer/playContent()
at runtime::AppRunner/run()
at ADLAppEntry/run()
at global/runtime::ADLEntry()
The Code for PlayScreen is:
import flashx.textLayout.formats.BackgroundColor;
import flash.display.SimpleButton;
import flash.ui.Mouse;
import flash.text.TextField;
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class PlayScreen extends MovieClip
{
public var batArmy:Array;
public var hockArmy:Array;
public var shadow:Shadow;
public var crossHairs:CrossHairs;
var Layer01:MovieClip;
var Layer02:MovieClip;
var Layer03:MovieClip;
var Layer04:MovieClip;
var Layer05:MovieClip;
var randomX:Number = 300 + (660 - 300) * Math.random();
public function PlayScreen()
{
//Mouse.hide();
addBatButton.addEventListener(MouseEvent.CLICK, addBat);
addHockButton.addEventListener(MouseEvent.CLICK, addHock);
batArmy = new Array();
hockArmy = new Array();
//addEventListener(Event.ENTER_FRAME, crossHairsMove);
//stage.addEventListener( KeyboardEvent.KEY_DOWN, onKeyPress );
Layer01 = new MovieClip;
this.addChild(Layer01);
Layer02 = new MovieClip;
this.addChild(Layer02);
Layer03 = new MovieClip;
this.addChild(Layer03);
Layer04 = new MovieClip;
this.addChild(Layer04);
Layer05 = new MovieClip;
this.addChild(Layer05);
//add crossHair
/*crossHairs = new CrossHairs(mouseX,mouseY,this);
Layer05.addChild (crossHairs);
addEventListener(Event.ENTER_FRAME, crossHairsMove);*/
}
/*public function onKeyPress( keyboardEvent:KeyboardEvent ):void
{
if ( keyboardEvent.keyCode == Keyboard.DOWN )
{
trace("yar");
addBat;
}
}*/
public function addBat( mouseEvent:MouseEvent ):void
{
var randomX:Number = 300 + (660 - 300) * Math.random();
var newBat = new Bat( randomX, -50, this);
batArmy.push ( newBat );
Layer02.addChild (newBat);
}
public function addHock( mouseEvent:MouseEvent ):void
{
var newHock = new Hock(-72, 170, this);
hockArmy.push ( newHock );
Layer02.addChild (newHock);
}
/*public function crossHairsMove ( e:Event ):void
{
crossHairs.x = mouseX;
crossHairs.y = mouseY;
}*/
}
and from the looks of it the error has something to do with the Hock class, so here's the code for that:
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class Hock extends MovieClip
{
private var _screen: PlayScreen;
public var xSpeed:Number;
public function Hock( startX:Number, startY:Number, screen:PlayScreen )
{
_screen = screen;
x = startX;
y = startY;
width = 100;
scaleY = scaleX;
addEventListener(Event.ENTER_FRAME, moveRightFar);
addEventListener(Event.ENTER_FRAME, moveSpeed)
}
public function moveSpeed( e:Event ):void
{
x += xSpeed;
}
public function moveRightFar ( e:Event): void
{
if (x < 0)
{
gotoAndStop("rollRight");
xSpeed = 13;
}
else if (x >= 240)
{
gotoAndStop("still")
xSpeed = 0;
}
}
}
Now I could be wrong but I think it's having a problem with var newHock = new Hock(-72, 170, this); in the "addHock" function, but I have 3 arguments there, not 0. Right? Anyway, like I said, it's not keeping the game from running but it is kind of annoying, so any insight is welcome. I'm sure it's something obvious. Thanks!
I have a guess, but I'll explain how i got there first ...
the first line of the stacktrace pointing at your source code is
at PlayScreen()[Z:\PROJECTS\Silversound\Occulus Squish\Oculus Squish\Classes\PlayScreen.as:30]
which points at the first line of the constructor of PlayScreen: addBatButton.addEventListener(MouseEvent.CLICK, addBat);
but obviously the problem is not there ...
But PlayScreen extends MovieClip and since you didn't specifically included a super() statement, the compiler will put that at as the first command. In fact, the previous lines of the stack point to the constructor of MovieClip and then to a mysterious constructChildren() method of Sprite
That happens to be an internal method used to create the childs of the Sprite that you might have setup on your clip's stage directly from Animate.
So my guess is, the player is trying to instantiate a symbol that extends Hock and that you positioned on the stage somewhere, and of course is doing it by passing zero arguments because that's what a normal Sprite would expect.
Check your library to see what extends Hock and then see which one of those is placed in some other symbol's stage. Your options then will be to remove that and create it from code or to rework the class signature to take zero arguments.

Unity 5.2 UNet: Release a GameObject from it's owner

I am testing UNET (Unity 5.2) but is running into problem with things that probably should be very simple.
I have an Orange fruit (GameObject) that i can drag and have attached the network transform in code. When releasing the mouse (Mouse Up) I want to release the ownership of the Orange so none owns it, want later to attach to another player. I have tested with ReplacePlayerForConnection and a few other things but totally screwed up the code.
I have now reset everything and must ask for some help how to do this.
The scripts i have, attached to the Orange GameObject, is:
1
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class orange : NetworkBehaviour {
float distance = 10;
void Start() {
if (isLocalPlayer) {
//GameObject.Find("Main Camera").SetActive(false);
}
}
void OnMouseDrag() {
Vector3 mousePosition = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint (mousePosition);
transform.position = objPosition;
}
void OnMouseUp() {
print (">>> MOUSE UP <<<");
if (isLocalPlayer) {
GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
GetComponent<NetworkIdentity> ().serverOnly = false;
}
}
Here is scrip #2 attached to the Orange GameObject:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Orange_SyncPosition : NetworkBehaviour {
[SyncVar] // Server will automatically transmit this value to all players when it changes
private Vector3 syncPos;
[SerializeField] Transform myTransform;
[SerializeField] float lerpRate = 15;
void FixedUpdate () {
TransmitPosition ();
LerpPosition ();
}
void LerpPosition() {
if (!isLocalPlayer) {
myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime *lerpRate);
}
}
[Command]
void CmdProvidePositionToServer (Vector3 pos) {
syncPos = pos;
}
[ClientCallback]
void TransmitPosition () {
if (isLocalPlayer) {
CmdProvidePositionToServer (myTransform.position);
}
}
}
Use NetworkServer.ReplacePlayerForConnection():
// Player is a NetworkBehaviour on the existing player object
void ReplacePlayer (Player existingPlayer) {
var conn = existingPlayer.connectionToClient;
var newPlayer = Instantiate<GameObject>(playerPrefab);
Destroy(existingPlayer.gameObject);
NetworkServer.ReplacePlayerForConnection(conn, newPlayer, 0);
}
Use AssignClientAuthority / RemoveClientAuthority
And never touch these parameters at runtime:
GetComponent<NetworkIdentity> ().localPlayerAuthority = false;
GetComponent<NetworkIdentity> ().serverOnly = false;

How to draw a line on a bitmap in Stage3D using Agal?

How can I draw a line on a bitmap in Stage3D using Agal? Can someone provide a code example?
If you use Starling you can try this:
/**
* Class Line
* #author Leandro Barreto 2012
* #version 1.0
**/
package starling.utils
{
import starling.display.Quad;
import starling.display.Sprite;
public class Line extends Sprite
{
private var baseQuad:Quad;
private var _thickness:Number = 1;
private var _color:uint = 0x000000;
public function Line()
{
baseQuad = new Quad(1, _thickness, _color);
addChild(baseQuad);
}
public function lineTo(toX:int, toY:int):void
{
baseQuad.width = Math.round(Math.sqrt((toX*toX)+(toY*toY)));
baseQuad.rotation = Math.atan2(toY, toX);
}
public function set thickness(t:Number):void
{
var currentRotation:Number = baseQuad.rotation;
baseQuad.rotation = 0;
baseQuad.height = _thickness = t;
baseQuad.rotation = currentRotation;
}
public function get thickness():Number
{
return _thickness;
}
public function set color(c:uint):void
{
baseQuad.color = _color = c;
}
public function get color():uint
{
return _color;
}
}
}
Someone suggested at the Starling forums that we create a Line class which draws a few quads connecting two points. This tutorial shows how to create polygons using AGAL for shaders:
http://wiki.starling-framework.org/manual/custom_display_objects
I recently wrote a simple library to draw lines on Stage3D.
It's called Zebroid, https://github.com/luwes/Zebroid
Zebroid does not support line caps or joints yet.

AS3 - Error #1009: Cannot access a property or method of a null object reference

I'm getting the following error when trying to run a short piece of code I'm making for use of a particle effect library.
Error #1009: Cannot access a property or method of a null object reference
I originally had my entire code running from Main and it worked fine, when I decided to put it into a "ParticleManager" class I begun getting this error.
The error itself happens here -
stage.addEventListener(MouseEvent.CLICK, _onStageMouseDown);
function _onStageMouseDown(e:MouseEvent):void
{
//Draws an explosion on to the screen at the position of the mouse click.
var emitter:Emitter3D = new ParticleExplosion(new Vector3D(mouseX- width/2, mouseY- height/2, 0));
renderer.addEmitter( emitter );
emitter.start();
trace(e);
trace(renderer.mouseX)
trace(renderer.mouseY)
}
}
It occurs on the first line there. And I've tried to research it and found this occurs because the stage is not set to anything, but how do I get around that? Why did it work fine running from Main before hand?
Thanks!
Edit - Additional information requested.
The Main class
package
{
import flash.display.Sprite;
[SWF(width='800', height='600', frameRate='60', backgroundColor='#000000')]
/**
* ...
* #author
*/
public class Main extends Sprite
{
private var pManager:ParticleManager;
public function Main()
{
pManager = new ParticleManager;
}
}
}
The ParticleManager class, which before was identical just named "Main" and would run from that.
package
{
//Flint imports
import flash.events.Event;
import flash.events.MouseEvent;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.actions.ScaleImage;
import org.flintparticles.common.events.EmitterEvent;
import org.flintparticles.common.events.ParticleEvent;
import org.flintparticles.threeD.emitters.Emitter3D;
import org.flintparticles.threeD.particles.Particle3D;
import org.flintparticles.threeD.renderers.BitmapRenderer;
import org.flintparticles.threeD.renderers.controllers.FirstPersonCamera;
import org.flintparticles.threeD.zones.LineZone;
//Flash imports
import flash.display.Sprite;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.geom.Rectangle;
import flash.geom.Vector3D;
/**
* ...
* #author
*/
public class ParticleManager extends Sprite
{
private var orbitter:FirstPersonCamera;
private var renderer:BitmapRenderer;
public function ParticleManager()
{
//Sets up the "BitMapRenderer" a rectangle where the particle effects will be drawn on to
renderer = new BitmapRenderer( new Rectangle( 0, 0, 800, 600 ), false );
renderer.x = 0;
renderer.y = 0;
renderer.addFilter( new BlurFilter( 2, 2, 1 ) );
renderer.addFilter( new ColorMatrixFilter( [ 1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0.95,0 ] ) );
addChild( renderer );
renderer.camera.position = new Vector3D( 0, 0, -400 );
renderer.camera.target = new Vector3D( 0, 0, 0 );
renderer.camera.projectionDistance = 400;
//Mouse click
function addedToStageHandler(event:Event):void
{
stage.addEventListener(MouseEvent.CLICK, _onStageMouseDown);
}
function _onStageMouseDown(e:MouseEvent):void
{
//Draws an explosion on to the screen at the position of the mouse click.
var emitter:Emitter3D = new ParticleExplosion(new Vector3D(mouseX- width/2, mouseY- height/2, 0));
renderer.addEmitter( emitter );
emitter.start();
trace(e);
trace(renderer.mouseX)
trace(renderer.mouseY)
}
}
public function removeEmitter( ev:EmitterEvent ):void
{
Emitter3D( ev.target ).removeEventListener( EmitterEvent.EMITTER_EMPTY, removeEmitter );
renderer.removeEmitter( Emitter3D( ev.target ) );
}
public function destroy():void
{
for each( var e:Emitter in renderer.emitters )
{
e.stop();
}
}
}
}
Most likely it's not added to stage; therefore, stage is null when the code executes.
Listen for added to stage, then execute that code:
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
function addedToStageHandler(event:Event):void
{
stage.addEventListener(MouseEvent.CLICK, _onStageMouseDown);
}
Previously from your Main, it was probably already added to stage.
From Main, I don't see how the particle manager is added to the display list. I believe you just need to add your particle manager to Main:
package
{
import flash.display.Sprite;
[SWF(width = '800', height = '600', frameRate = '60', backgroundColor = '#000000')]
public class Main extends Sprite
{
private var pManager:ParticleManager;
public function Main()
{
pManager = new ParticleManager;
addChild(pManager);
}
}
}

Blackberry: why is drawListRow() called with different y for ListField and KeywordFilterField

I'm trying to move an app from using a KeywordFilterField to ListField and I'm struggling since several hours to find out, why is drawListRow() called with different y values - depending on which of these two ListField's I use:
If getRowHeight() returns 40, then the y values will be -
For KeywordFilterField are: 0; 40; 80; 120; ... (i.e. as expected)
But for Listfield I see: 9; 49; 89; 129; ... (i.e. offset by 9 for some reason)
Where is the 9 coming from? Is there a method in ListField or ListFieldCallback which I could call to get this value? I'm just trying to draw a light gray line between items of the list.
Below is my test code and the border.png (used as BasicEditField border) is attached:
package mypackage;
import java.util.*;
import net.rim.device.api.collection.*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.decor.*;
import net.rim.device.api.util.*;
public class MyList extends UiApplication {
public static void main(String args[]) {
MyList app = new MyList();
app.enterEventDispatcher();
}
public MyList() {
pushScreen(new MyScreen());
}
}
class MyScreen extends MainScreen {
static final int EXTRA_ROWS = 2;
MyItemList myItems = new MyItemList();
ListField myList = new ListField(EXTRA_ROWS);
Border myBorder = BorderFactory.createBitmapBorder(
new XYEdges(12, 12, 12, 12),
Bitmap.getBitmapResource("border.png"));
Background myBg = BackgroundFactory.createSolidBackground(0x111111);
StringProvider myProvider = new StringProvider("Search");
BasicEditField myFind = new BasicEditField(USE_ALL_WIDTH) {
protected void paint(Graphics g) {
if (getTextLength() == 0) {
g.setColor(Color.LIGHTGRAY);
g.drawText(myProvider.toString(), 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
};
public MyScreen() {
getMainManager().setBackground(myBg);
myFind.setBorder(myBorder);
setTitle(myFind);
myItems.doAdd(new MyItem(1, "Eins"));
myItems.doAdd(new MyItem(2, "Zwei"));
myItems.doAdd(new MyItem(3, "Drei"));
myItems.doAdd(new MyItem(4, "Vier"));
myList.setCallback(new MyListFieldCallback());
add(myList);
}
private class MyListFieldCallback implements ListFieldCallback {
public void drawListRow(ListField list, Graphics g, int index, int y, int width) {
System.err.println("XXX index=" + index+ ", y=" + y + ", width=" + width);
g.setColor(Color.WHITE);
if (index < EXTRA_ROWS) {
Font i = getFont().derive(Font.ITALIC);
g.setFont(i);
g.drawText("Add Item", 0, y);
return;
}
if (index >= EXTRA_ROWS) {
MyItem item = (MyItem) myItems.getAt(index - EXTRA_ROWS);
g.drawText(item.toString(), 0, y);
g.setColor(0x333333);
// XXX why do I need to subtract 9 here?
g.drawLine(0, y-9, width, y-9);
return;
}
g.drawText(list.getEmptyString(), 0, y);
}
public Object get(ListField list, int index) {
return myItems.getAt(index);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
public int indexOfList(ListField list, String prefix, int start) {
return 0;
}
}
class MyItemList extends SortedReadableList {
public MyItemList() {
super(new MyItem.MyComparator());
}
protected void doAdd(Object obj) {
super.doAdd(obj);
myList.setSize(size() + EXTRA_ROWS);
}
protected boolean doRemove(Object obj) {
myList.setSize(size() - 1 + EXTRA_ROWS);
return super.doRemove(obj);
}
}
}
class MyItem {
int _num;
String _name;
public MyItem(int num, String name) {
_num = num;
_name = name;
}
public String toString() {
return _num + ": " + _name;
}
static class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
MyItem item1 = (MyItem) obj1;
MyItem item2 = (MyItem) obj2;
return item1.toString().compareTo(item2.toString());
}
}
static class MyProvider implements KeywordProvider {
public String[] getKeywords(Object obj) {
MyItem item = (MyItem) obj;
return new String[]{ Integer.toString(item._num), item._name };
}
}
}
The produced output is:
[ 64,890] XXX index=0, y=9, width=360
[ 64,890] XXX index=1, y=49, width=360
[ 64,898] XXX index=2, y=89, width=360
[ 64,898] XXX index=3, y=129, width=360
[ 64,906] XXX index=4, y=169, width=360
[ 64,906] XXX index=5, y=209, width=360
UPDATE in reply to jprofitt
When I try your suggestion (I use red color for your text and lines):
if (index >= EXTRA_ROWS) {
MyItem item = (MyItem) myItems.getAt(index - EXTRA_ROWS);
g.drawText(item.toString(), 0, y);
g.setColor(Color.RED);
g.drawText("XXX", 0, y + (list.getRowHeight() - list.getFont().getHeight())/2);
g.setColor(0x333333);
// XXX why do I need to subtract 9 here?
g.drawLine(0, y-9, width, y-9);
g.setColor(Color.RED);
g.drawLine(0, y, width, y);
return;
}
Then it doesn't really work - because the blue focus line does not align with your suggested (red) lines. It aligns with my (gray) lines, which means you really need to subtract -9 for some reason:
Thank you!
Alex
Yes, this is an odd behaviour. I guess this is smth OS 6 specific. Looks like in OS 6 ListField became so clever that it passes Y coordinate already prepared for direct usage in text drawing, so you don't have to do manual calculation (usually I calculate Y for text drawing in the same way jprofitt suggests). So assuming my guess is true I changed the code as follows:
if (index >= EXTRA_ROWS) {
MyItem item = (MyItem) myItems.getAt(index - EXTRA_ROWS);
g.drawText(item.toString(), 0, y);
g.setColor(0x333333);
// XXX why do I need to subtract 9 here?
// use the offset instead
int offset = (myList.getRowHeight() - getFont().getHeight()) >> 1;
g.drawLine(0, y - offset, width, y - offset);
return;
}
and it works fine (tested on all font sizes that are available in device settings).
Alright I believe I got this figured out. What is going on is that your row height is greater than the font height. So when you draw your text right at y, you are drawing it top aligned to the actual row. In my case, row height was 40 and font height was 20. Half of that difference is where your y - 9 was coming in. If you change your drawText() calls to this, it should work without needing to subtract anything when drawing the line:
g.drawText(theString, 0, y + (list.getRowHeight() - list.getFont().getHeight())/2);
You could cache the font height and row height so you don't have to do the calculations in paint(), for efficiency's sake.

Resources