Sprite Movement
Hi i was wondering if its possible to get a sprite to move
accross the stage, then when clicked on it changes to a different
sprite, plays a sound and resets to its original position to start
over again?
currently i have the sprite moving across the screen once,
and the sprite i want to replace the original with appears in the
center of the stage when i click, not where the first sprite was.
on mouseup me
sprite(2).member="picture2"
Hopefully someone understands what i'm trying to do. Any help
would be great
thanks
Mark
property pSprite
property pStartLoc
property pTargetLoc
property pStep
property pFrames
on beginSprite(me)
pSprite = sprite(me.spriteNum)
pStartLoc = pSprite.loc
pTargetLoc = point(0, 0) -- or wherever
pFrames = 30 -- number of frames to reach target
pStep = (pStartLoc - pTargetLoc) / float(pFrames)
end
on enterFrame(me)
if not pFrames then
exit
end if
pFrames = pFrames - 1
vLoc = pTargetLoc + pFrames * pStep
pSprite.loc = vLoc
end enterFrame
on mouseUp(me)
pSprite.member = me.mGetMember()
pSprite.loc = pStartLoc
puppetSound(1, "MouseUp Sound")
pFrames = 30
end
on mGetMember(me)
return pSprite.member -- or something more imaginative
end
Similar Messages
-
Sprite movement using arrow keys
Hello,
I have been working on a dragonball z game recently and I
have encountered a problem with the sprites.I have traced the
bitmap and everything else and even created a movieclip of the
sprite.I have put this code on the movieclip-
Code: ( text )
onClipEvent (load) {
step = 5;
onClipEvent (enterFrame) {
if (Key.isDown(Key.RIGHT) && this._x<550) {
this._x += step;
gotoAndPlay(2);
} else if (Key.isDown(Key.LEFT) && this._x>0) {
this._x -= step;
gotoAndPlay(10);
} else if (Key.isDown(Key.UP) && this._y>0) {
this._y -= step;
gotoAndPlay(15);
} else if (Key.isDown(Key.DOWN) && this._y<400) {
this._y += step;
gotoAndPlay(6);
I have put animations of the character walking on the
differnet frames inside the movieclip.For eg-
I have shown the character walking right from frame
2-5,walking down from frame 6-9,walking left from
frame10-14,walking up from frame 15-19.
THE PROBLEM is that whenever I press a specefic key(I will
take the example of right) and keep it pressed,IT DOES NOT PLAY THE
WHOlE ANI:MATION OF MOVING RIGHT.It just plays frame 2 and repeats
it instead of playing frames 2-5 together.
HELP is required!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hi chinmayagoyal,
the problem is that your clip will be sent to frame 2, 10,
15, or 6 every time you press a key. So when you keep the key
pressed, it will keep sending the clip to that frame. You should
check if the animation is at a certain point.
Example: right movement: frame 2 to 6
if (Key.isDown(Key.RIGHT) && this._x<550) {
this._x += step;
if(this._currentframe==1 or this._currentframe>5){
gotoAndPlay(2);
Good luck,
Rick. -
Will this function help keep my sprites moving at a consistant # of pixels / second no matter the # of iterations my main game loop does per second? Is there a better approach? I have this calculation at the Sprite level, so it is done for each sprite. Should this be at the game loop level, and passed to each sprite at each move call?
private long lastDrawTime = 0;
private int defaultMovePixel = 100 ; /* 100 pixels per second */
public void moveSprite()
long delay = System.currentTimeMillis()-lastDrawTime ;
int movePx = (int) ( (defaultMovePixel * delay) / 1000L );
if( isRight() )
setX( getX()+movePx );
if( isLeft() )
setX( getX()-movePx );
if( isDown() )
setY( getY()+movePx );
if( isUp() )
setY( getY()-movePx );
}What I do is, project the sprite's movement when the movement starts, and instantiate an object which knows how to calculate the sprite's position at any point in time.
I also keep the sprite's position in sub-pixel measurements to gain a teeny bit more smoothness when multiples of these movements are done in succession (usually left-shift-4, or 1/16 of a pixel).
I've seen this approach called to timing called 'alpha' in APIs like Java3D. I'm pretty sure Quake 3 and probably other games of a similar nature use the same sort of algorithm for projectile movement. I remember JC talking about changing to this style from the previous 'delta' style (delta is what you were describing.) -
Sample for Sprite Tracks movie
Can anybody Please post the Sample of Sprite movie. I search google i could not find a single online quicktime movie which uses the Sprite Tracks.
Please I would really appreciate it.....
Also what are these .dmg file and and what does it do??? I know that its Mac OS Disk Image file but is it movie or just code.
Please Help me here ASAP,
Thanks,Here's a page of sprite movies that you can attach to your own QuickTime movie in order to give it some interactivity.
http://homepage.mac.com/qt4web/sprites/items.html
Also you can use eZediaQTI
http://www.ezedia.com/products/eZediaQTI/
(for Mac and PC)
in order to create movies with custom sprites. I used it to create the two sprite enabled QuickTime media skins on this page.
http://homepage.mac.com/makentosh/QTITest
Message was edited by: Kyn Drake -
Trying to make object move parabolically....
Im creating a race track where an object goes around in laps.. So far, the object is moving at straight 90 degree angles when it hits sides.. Im trying, and also wondering how to make the object curve when it turns a corner instead of hitting the edge, then turning a full 90 degree angle.... Im really stumped, first year takin Java :(
Here's what I got so far:
// The "Race" class.
import java.applet.*;
import java.awt.*;
public class Race extends Applet implements Runnable
Dimension d = getSize ();
Font f;
int counter = 0;
int xchange;
int ychange;
int x = 50;
int y = d.height - 50;
boolean beg = false;
boolean slow = false;
boolean medi = false;
boolean fast = false;
Button start, slo, med, fas, stop;
TextField output;
Thread t;
Graphics bufferg;
Image buffer;
Image CARu, CARd, CARl, CARr, bakg;
AudioClip intro, test;
public void init ()
test = getAudioClip (getCodeBase (), "1.au");
intro = getAudioClip (getCodeBase (), "laser.au");
Dimension d = getSize ();
buffer = createImage (d.width, d.height);
bufferg = buffer.getGraphics ();
start = new Button ("Start");
start.setBackground (Color.yellow);
add (start);
slo = new Button ("Slow");
slo.setBackground (Color.yellow);
add (slo);
med = new Button ("Medium");
med.setBackground (Color.yellow);
add (med);
fas = new Button ("Fast");
fas.setBackground (Color.yellow);
add (fas);
stop = new Button ("Stop");
stop.setBackground (Color.yellow);
add (stop);
CARu = getImage (getCodeBase (), "carUP.jpg");
CARd = getImage (getCodeBase (), "carDOWN.jpg");
CARl = getImage (getCodeBase (), "carLEFT.jpg");
CARr = getImage (getCodeBase (), "carRIGHT.jpg");
bakg = getImage (getCodeBase (), "bakg.jpg");
public boolean action (Event e, Object o)
if (e.target == start)
beg = true;
test.loop ();
intro.play ();
if (e.target == slo)
slow = true;
medi = false;
fast = false;
if (e.target == med)
slow = false;
medi = true;
fast = false;
if (e.target == fas)
slow = false;
medi = false;
fast = true;
if (e.target == stop)
beg = false;
slow = false;
medi = false;
fast = false;
counter = 0;
x = 50;
y = d.height - 50;
return true;
public void start ()
if (t == null)
t = new Thread (this);
t.start ();
public void stop ()
if (t != null)
t.stop ();
t = null;
public boolean keyDown (Event e, int key)
if (key == 's')
intro.stop ();
return true;
public void run ()
while (true)
//Thread sleeps for 15 milliseconds here
try
t.sleep (15);
catch (Exception e)
Dimension d = getSize ();
bufferg.setColor (Color.green);
bufferg.fillRect (0, 0, d.width, d.height);
// (d.width-50) ((d.height/3) -50)
bufferg.drawImage (bakg, 0, 0, this);
bufferg.setColor (Color.red);
xchange = 0;
ychange = 0;
if (beg == true)
if (x <= (d.width - 50) && y >= (d.height - 50))
xchange = 1;
if (slow == true)
ychange = 1;
xchange = 1;
if (medi == true)
ychange = 2;
xchange = 2;
if (fast == true)
ychange = 6;
xchange = 6;
bufferg.fillOval (x, d.height - 50, 50, 50);
//bufferg.drawImage (car_r, x, 300, this);
x += xchange;
if (x >= (d.width - 50) && y >= ((d.height / 3) - 50))
ychange = 1;
if (slow == true)
ychange = 1;
xchange = 1;
if (medi == true)
ychange = 2;
xchange = 2;
if (fast == true)
ychange = 6;
xchange = 6;
bufferg.fillOval ((d.width - 50), y, 50, 50);
// bufferg.drawImage (car_u, 350, y, this);
y -= ychange;
if (y <= ((d.height / 3) - 50) && x >= 50)
xchange = 1;
if (slow == true)
ychange = 1;
xchange = 1;
if (medi == true)
ychange = 2;
xchange = 2;
if (fast == true)
ychange = 6;
xchange = 6;
bufferg.fillOval (x, ((d.height / 3) - 50), 50, 50);
//bufferg.drawImage (car_l, x, 115, this);
x -= xchange;
if (x <= 50 && y <= (d.height - 50))
ychange = 1;
if (slow == true)
ychange = 1;
xchange = 1;
if (medi == true)
ychange = 2;
xchange = 2;
if (fast == true)
ychange = 6;
xchange = 6;
bufferg.fillOval (50, y, 50, 50);
//bufferg.drawImage (car_d, 50, y, this);
y += ychange;
if ((x <= 50) && (y <= (d.width - 50)) && (x <= (d.width - 50)) && (y >= (d.height - 50)))
counter++;
else
{ //bufferg.drawImage (car_r, 50, 300, this);
x = 50;
y = d.height - 50;
bufferg.fillOval (x, y, 50, 50);
repaint ();
public void update (Graphics g)
paint (g);
public void paint (Graphics g)
bufferg.setColor (Color.red);
f = new Font ("Test", Font.BOLD, 25);
bufferg.setFont (f);
bufferg.setColor (Color.blue);
bufferg.drawString ("Lap " + counter, 300, 300);
g.drawImage (buffer, 0, 0, this);
} // paint method
} // Race classCan anyone help me please?here's a stripped down bounded sprite engine. use the arrows keys. up=accelerate forward. down=accelerate backwards. left=turn left. right=turn right. supply a 32x32 image named "image.jpg" (or write your filename in the code below) to see the picture rotate as it corners. otherwise, you'll just see non rotating colored squares which represent the bounding box of the image. the variable turns is the number of images you will have on the screen at a time. i should have chosen a better variable name.
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
public class SpriteEngine extends Applet implements Runnable, KeyListener{
Graphics2D dbg;
Image dbImage;
public int gameSpeed = 100;
public int turns = 10;
Thread th;
boolean forward=false, reverse=false, left=false,right=false;
Sprite[] sprite = new Sprite[turns];
public void init(){
setSize(500,500);
setBackground(Color.black);
addKeyListener(this);
Image image = getImage(getCodeBase(),"image.jpg");
for(int a=0;a<turns;a++){
sprite[a]=new Sprite(image, new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)), new Point((int)(Math.random()*500),(int)(Math.random()*500)), Math.random()*360,Math.random()*12-6);
public void start (){
th = new Thread (this);
th.start ();
public void run () {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true){
checkControls();
for(int i=0;i<turns;i++){
sprite.move();
repaint();
try {
th.sleep (gameSpeed);
}catch (InterruptedException ex){
public void paint (Graphics2D g) {
for(int a=0;a<turns;a++){
sprite[a].draw(g);
g.setColor(Color.black);
public void update (Graphics g) {
if (dbImage == null){
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = (Graphics2D)dbImage.getGraphics();
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==38){forward=true;}else
if (e.getKeyCode()==40){reverse=true;}else
if (e.getKeyCode()==37){left=true; }else
if (e.getKeyCode()==39){right=true; }
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==38){forward=false;}else
if (e.getKeyCode()==40){reverse=false;}else
if (e.getKeyCode()==37){left=false; }else
if (e.getKeyCode()==39){right=false; }
public void keyTyped(KeyEvent e) {}
public void checkControls(){
for(int a=0;a<turns;a++){
if (forward){sprite[a].accel() ;}
if (reverse){sprite[a].deccel() ;}
if (left) {sprite[a].turnLeft() ;}
if (right) {sprite[a].turnRight();}
class Sprite extends Object {
private Image image;
AffineTransform imageLocation=new AffineTransform();
double velocity;
Rectangle bounds;
Rectangle refShape=new Rectangle(32,32);
double MaxSpeed=6;
double AccelRate=.3;
public double Rotation=6;
double posX,posY,angle;
Color boxColor;
public boolean keyDown = false;
double dx,dy;
public Sprite(Image img, Color color, Point location, double ang, double speed){
posX=location.x; posY=location.y; boxColor = color;
image=img; velocity=speed; angle=ang;
bounds=new Rectangle((int)posX,(int)posY,32,32);
public void draw(Graphics2D g){
g.setColor(boxColor);
g.fill((bounds));
g.setColor(Color.black);
g.drawImage(image,imageLocation,null); //this draws your image with the AffineTranform applied
public void setLocation(Point point) {posX=point.x; posY=point.y; }
public Point getLocation() {return bounds.getLocation();}
public void setBounds(Rectangle rect){bounds=rect; }
public Rectangle getBounds() {return bounds; }
public void setSpeed(double speed) {velocity=speed; }
public double getSpeed() {return velocity; }
public void setAngle(double theta) {angle=theta; }
public double getAngle() {return angle; }
public void turnLeft() {angle=angle-Rotation; }
public void turnRight() {angle=angle+Rotation; }
public AffineTransform getForm() {return imageLocation; }
public void setForm(AffineTransform xform){ }
public void accel(){if(velocity<MaxSpeed){velocity=velocity+AccelRate;}}
public void deccel(){if(velocity> -MaxSpeed){velocity=velocity-AccelRate;}}
public void move(){
dx=Math.cos(Math.toRadians(angle))*velocity;
dy=Math.sin(Math.toRadians(angle))*velocity;
posX=posX+dx;
posY=posY+dy;
imageLocation=AffineTransform.getTranslateInstance(posX,posY); //these two line set the affinetransform
imageLocation.rotate(Math.toRadians(angle)+Math.PI/2,16,16); //to the right place and angle.
bounds.setLocation((int)posX,(int)posY);
if(!keyDown){
if (velocity<0){
velocity=velocity+.15; // -drag
}else if (velocity>0){
velocity=velocity - 0.15; // +drag -
Help!! Putting a sprite on a path?
I'm looking for a similar program to this, except it needs to be a circle which gets bigger as it goes along a Sprite Path and forms a pattern. The path will start at the top left and finish at the bottom right with circles being created as the Sprite moves along the path.
import animax.*;
import java.awt.Rectangle;
class MovingCircle
public static void main(String[ ] args)
Stage stage = (new AnimationFrame(500, 300, 120)).getStage();
Rectangle rect = new Rectangle(0, 0, 100, 50);
stage.add(new SpritePath(100, 150, 450, 50, sprite));
stage.add(new SpritePathDisplay( ));
This progam makes circles bigger.
import animax.*;
class circles
public static void main(String[] args)
int x = 350, y = 350;
int r = 50;
int dr = 10;
GrafixDrawingFrame f = new GrafixDrawingFrame(700,650);
f.drawOval(x - r, y-r, 2*r, 2*r); r = r + dr;
f.drawOval(x - r, y-r, 2*r, 2*r); r = r + dr;
f.drawOval(x - r, y-r, 2*r, 2*r); r = r + dr;
}Moire pattern that moves along a path.
Message was edited by:
helloworld2007old mrs fuzzy-wuzzy had a square-cut punt. not a punt cut square, but a square-cut punt -
Moving sprite at random intervals
Hi can anyone help please -
I'm currently making a game for an assignment, and i want to
make the sprites move from the left of the screen to the right, and
appear at random time intervals. I am using the following code at
the minute, but it is only making the sprite move back and forward
across the stage, not go from left to right.
If someone could point me in the right direction that would
be great thanks.
TimHi Tim,
No code appeared in your messsage. Try attaching it using the
"attach code" button
in the forum. There are issues with writing code in here if
it's just put as part
of your normal message. Also, there is a Lingo forum, which
is usually the better
place for coding related questions.
regards
Dean
Director Lecturer / Consultant
http://www.fbe.unsw.edu.au/learning/director
http://www.multimediacreative.com.au -
Sprite.graphics performance issue...
Hello,
I have been working on a pretty big project in flash. To
start with, I designed my components in the authoring tool (mostly
because I did not have an idea on how I wanted them to look). Once
I got my story straight, I put everything together and I had a good
look at my application. It was great. It was moving so fast that I
couldn't believe it was flash...
Then, I started replacing the pre-drawn components with
Sprites and Shapes drawn in AS3 via Sprite/Shape.graphics and
adding them as child with Sprite.addChild.
I absolutely DID NOT change anything else.
By the time I was finished, I noticed that my great
performance was not there anymore... For example: I have a
scrolling feature (when I click a sprite a few other sprites move
up a few lines). It used to be instantaneous. Now there is a delay
of about 1 second or more between the release of the mouse button
and the actual scrolling. (Also, I have the previous version of the
project and I can clearly see the time difference. So I am not
imagining things :)).
I have backtracked my work several times and there is no "one
thing" that causes this... it just ads up as I convert from
pre-drawn components to dynamically drawn ones.
Also, I should mention that all my pre-drawn components were
sprites with "Instance Names" (not shapes with no name).
So, my question is: is there a performance difference between
using Sprites pre-drawn in the authoring tool versus Sprites
created in AS3?
Appreciate all the help. Thank you.
Tony
PS: I can not go back to pre-drawn components because that
will take away from the flexibility of the application.These instructions must be carried out as an administrator, if you have more than one account.
Launch the Console application in any of the following ways:
☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left.
Copy the text on the line below:
smcHandleInterruptEvent
and paste it in the Filter text field. You may see some messages like this:
SMC::smcHandleInterruptEvent WARNING status=0x0 (0x40 not set) notif=0x0
The timestamps of those messages (if any) indicate the times, since the log was last cleared, when the processor was being throttled because of high temperature. -
How to stay in full screen mode when the movie is end
for some commercial reason, I need quicktime to stay in full screen mode when a movie playing is end.How can I config it? Thanks a lot.
You can place what i called a sprite in the video.
http://homepage.mac.com/qt4web/sprites/items.html
Scroll down the web page a little bit and you'll find it. You place the stop sprite a few seconds before the end of the video.
Right click on or control+click on stopsprite.mov in the above web page to open the sprite in the Quicktime player.
Click on the sprite movie, 'select all' from the menu. Click on the video you want to stop. Go to about 5 second (more would better) before the end of the video. Hit the key i on the keyboard. Go to the end of the video and hit the key o (Oh). Go back up to Quicktime's menu--->Edit--->Add To Selection & Scale--->Save As and rename the video. Done....
If for some reason the video doesn't stop add more time....10 seconds before the end of the video.
Message was edited by: David M Brewer -
Hey guys,
I have a massive problem that I've been struggling over for days now. I have a green rectangle that a sprite can travel over. I have code set up to tell me what colour the next Pixel along is, but for some reason the sprite is seeing the edge of the rectangle sooner than it should be seen.
I'm not sure whether I have explained that very well.
The file is here, you will see what I mean.
My problem is on the "Level 1" Marker.
Please can somebody help, I'm desperate for an answer on this as my deadline is near.Try the following alterations to the script attached to your moveable character:
-- properties used in this script:
-- pSprite - the sprite reference
-- pSpeed - the speed the sprite should move
-- myLocH - the current horizontal position of the sprite
-- myLocV - the current vertical position of the sprite
property spriteNum
property my
property myReferenceImage
property myReferenceImageOffset
property myWidthOffset
property myHeightOffset
property pSprite, pSpeed, myLocH, myLocV
on beginSprite me
-- initialise sprite properties
my = sprite(spriteNum)
myReferenceImage = member("Level_1_Maze").image
-- reference bitmap is offset from (0, 0) by (9, 12)
myReferenceImageOffset = point(9, 12)
-- account for l, t, r, b colliding with "walls"
-- regPoint is centered, so:
myWidthOffset = my.width/2
myHeightOffset = my.height/2
-- controls the speed that the sprite moves at
pSpeed = 10
end
on keyPress me, aDirection
-- actions THIS sprite should take on key press
-- store current location
myLocH = my.locH
myLocV = my.locV
-- find which direction to move
case aDirection of
#left: me.goLeft()
#right: me.goRight()
#up: me.goUp()
#down: me.goDown()
end case
end
-- individual custom event handlers for movement
on goLeft me
-- swap the sprite for one based on the
-- left film loop cast member
my.member = member("left")
-- move the sprite to the left if no hedge to the left of the cast member
newlocH = myLocH - pSpeed
iColor = myReferenceImage.getPixel(point(newlocH - myWidthOffset, myLocV) - myReferenceImageOffset, #integer)
if iColor = -16720640 then
--grass colour is legal so allow move
my.locH = newLocH
else
put iColor
beep
end if
end
on goRight me
my.member = member("right")
newlocH = myLocH + pSpeed
iColor = myReferenceImage.getPixel(point(newlocH + myWidthOffset, myLocV) - myReferenceImageOffset, #integer)
if iColor = -16720640 then
--grass colour is legal so allow move
my.locH = newLocH
else
put iColor
beep
end if
end
on goUp me
my.member = member("up")
newLocV = myLocV - pSpeed
--find out if newLoc is a legal space
iColor = myReferenceImage.getPixel(point(myLocH, newLocV- myHeightOffset) - myReferenceImageOffset, #integer)
if iColor = -16720640 then
--grass colour is legal so allow move
my.locV = newLocV
else
put iColor
beep
end if
end
on goDown me
my.member = member("down")
newLocV = myLocV + pSpeed
--find out if newLoc is a legal space
iColor = myReferenceImage.getPixel(point(myLocH, newLocV + myHeightOffset) - myReferenceImageOffset, #integer)
if iColor = -16720640 then
-- grass colour is legal so allow move
my.locV = newLocV
else
put iColor
beep
end if
end
This could do with a degree more rationalisation/optimisation/consolidation yet. For example:
-- properties used in this script:
-- pSprite - the sprite reference
-- pSpeed - the speed the sprite should move
-- myLocH - the current horizontal position of the sprite
-- myLocV - the current vertical position of the sprite
property spriteNum
property my
property myReferenceImage
property myReferenceImageOffset
property myWidthOffset
property myHeightOffset
property pSprite, pSpeed, myLocH, myLocV
on beginSprite me
-- initialise sprite properties
my = sprite(spriteNum)
myReferenceImage = member("Level_1_Maze").image
-- reference bitmap is offset from (0, 0) by (9, 12)
myReferenceImageOffset = point(9, 12)
-- account for l, t, r, b colliding with "walls"
-- regPoint is centered, so:
myWidthOffset = my.width/2
myHeightOffset = my.height/2
-- controls the speed that the sprite moves at
pSpeed = 10
end
on keyPress me, aDirection
-- find which direction to move
case aDirection of
#left:
tMember = member("left")
tPoint = my.loc - point(pSpeed + myWidthOffset, 0)
#right:
tMember = member("right")
tPoint = my.loc + point(pSpeed + myWidthOffset, 0)
#up:
tMember = member("up")
tPoint = my.loc - point(0, pSpeed + myHeightOffset)
#down:
tMember = member("down")
tPoint = my.loc + point(0, pSpeed + myHeightOffset)
end case
my.member = tMember
iColor = myReferenceImage.getPixel(tPoint - myReferenceImageOffset, #integer)
if iColor = -16720640 then
--grass colour is legal so allow move
my.loc = tPoint
else
put iColor
beep
end if
end -
Moving a Sprite across the screen
If I use mySprite.x += 1; //it's choppy
if I use mySprite.x += .1; //it's smoother but slow
if I use mySprite.x += .5; //it's only slightly choppy but speed is better
Is there a way to guarantee perfect movement(the sprite moves subpixels), yet still have an adjustable speed?What's your framerate? 27 - 30fps is best.
Also, try using a tweening engine like TweenLite. That way you move based on time:
TweenLite.to(myClip, 3, {x:100});
would move myClip to x of 100 in 3 seconds.
http://www.greensock.com/tweenlite/ -
Ok, I have looked at everything and I have had several other people try and help me but I can not figure this out. My tanks rotation just isn't working right.
public void setVector()
//setting my degree measurement using my array of ints that represent my movement keys in ascii
baseTheta+=(controls[68]-controls[65]);
//setting my magnitude
incMove=controls[87]-controls[83];
//setting my vector
direction.set(incMove,Math.toRadians(baseTheta));
}I control the tank with a simple vector class(my instance of it is direction), that takes the sin and cos to determine the x and y.
public void set(double magnitude, double angle)
setX(magnitude * Math.cos(angle));
setY(magnitude * Math.sin(angle));
}Now, I have a thread that constantly calls the move method, which just incriments the x and y. My paint draw method within my tank class contains this
g2.setTransform(identity);
g2.translate(basePos.x,basePos.y);
g2.scale(baseScale,baseScale);
g2.rotate(Math.toRadians(baseTheta));
g2.setColor(baseColor);
g2.fill(baseShape);And so I just have it increment the x and y and then rotate it with the same variable, This seems to work except for a small problem. When you move backwards(which will make the magnitude a -10) and it has the same angle value as it was going forward, the images angle doesnt chang and is correct, but my X and Y are incrimented wrong. So if im going at an angle of say 30 degrees and moving forward it works fine. But when I move backwards my angle for rotation is correct and doesnt change, but my X and Y is out of wack and it doesnt move in the correct direction.here you go. this should help you.
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
public class SpriteExample extends Applet implements Runnable, KeyListener{
Graphics2D dbg;
Image dbImage;
public int gameSpeed = 100;
public int numOfImages = 2;
Thread th;
boolean forward=false, reverse=false, left=false,right=false;
Sprite[] sprite = new Sprite[numOfImages];
public void init(){
setSize(500,500);
setBackground(Color.black);
addKeyListener(this);
Image image = getImage(getCodeBase(),"image.jpg");
for(int a=0;a<numOfImages;a++){
sprite[a]=new Sprite(image, new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)), new Point((int)(Math.random()*500),(int)(Math.random()*500)), Math.random()*360,Math.random()*12-6);
public void start (){
th = new Thread (this);
th.start ();
public void run () {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true){
checkControls();
for(int i=0;i<numOfImages;i++){
sprite.move();
repaint();
try {
th.sleep (gameSpeed);
}catch (InterruptedException ex){
public void paint (Graphics2D g) {
for(int a=0;a<numOfImages;a++){
sprite[a].draw(g);
g.setColor(Color.black);
public void update (Graphics g) {
if (dbImage == null){
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = (Graphics2D)dbImage.getGraphics();
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==61){sprite[0].Rotation=sprite[0].Rotation+5;}
if (e.getKeyCode()==45){sprite[0].Rotation=sprite[0].Rotation-5;}
if (e.getKeyCode()==38){forward=true;}else
if (e.getKeyCode()==40){reverse=true;}else
if (e.getKeyCode()==37){left=true;}else
if (e.getKeyCode()==39){right=true;}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==38){forward=false;}else
if (e.getKeyCode()==40){reverse=false;}else
if (e.getKeyCode()==37){left=false;}else
if (e.getKeyCode()==39){right=false;}
public void keyTyped(KeyEvent e) {}
public void checkControls(){
for(int a=0;a<numOfImages;a++){
if (forward){sprite[a].accel() ;}
if (reverse){sprite[a].deccel() ;}
if (left) {sprite[a].turnLeft() ;}
if (right) {sprite[a].turnRight();}
class Sprite extends Object {
private Image image;
AffineTransform imageLocation=new AffineTransform();
double velocity;
Rectangle bounds;
Rectangle refShape=new Rectangle(32,32);
double MaxSpeed=6;
double AccelRate=.3;
public double Rotation=6;
double posX,posY,angle;
Color boxColor;
public boolean keyDown = false;
double dx,dy;
public Sprite(Image img, Color color, Point location, double ang, double speed){
posX=location.x; posY=location.y; boxColor = color;
image=img; velocity=speed; angle=ang;
bounds=new Rectangle((int)posX,(int)posY,32,32);
public void draw(Graphics2D g){
g.setColor(boxColor);
g.fill(bounds);
g.setColor(Color.black);
g.drawImage(image,imageLocation,null);
public void setLocation(Point point) {posX=point.x; posY=point.y; }
public Point getLocation() {return bounds.getLocation();}
public void setBounds(Rectangle rect){bounds=rect; }
public Rectangle getBounds() {return bounds; }
public void setSpeed(double speed) {velocity=speed; }
public double getSpeed() {return velocity; }
public void setAngle(double theta) {angle=theta; }
public double getAngle() {return angle; }
public void turnLeft() {angle=angle-Rotation; }
public void turnRight() {angle=angle+Rotation; }
public AffineTransform getForm() {return imageLocation; }
public void setForm(AffineTransform xform){ }
public void accel(){if(velocity<MaxSpeed){velocity=velocity+AccelRate;}}
public void deccel(){if(velocity> -MaxSpeed){velocity=velocity-AccelRate;}}
public void move(){
dx=Math.cos(Math.toRadians(angle))*velocity;
dy=Math.sin(Math.toRadians(angle))*velocity;
posX=posX+dx;
posY=posY+dy;
imageLocation=AffineTransform.getTranslateInstance(posX,posY);
imageLocation.rotate(Math.toRadians(angle)+Math.PI/2,16,16);
bounds.setLocation((int)posX,(int)posY);
if(!keyDown){
if (velocity<0){velocity=velocity+.15;}else if (velocity>0){velocity=velocity - 0.15;} -
Effect on Sprite breaks drag&drop mechanics
Hello,
I've a problem with applying effects to a number of SpriteVisualElements.
I had set up a grid of said sprites and could drag and drop them around using the startDrag() and stopDrag() methods.
I then decided to use effects to somehow animate these sprites when I click or drag them, and chose to play the effects in the handler of the MouseEvent.MOUSE_UP event.
Things still work, but.... some effects break the drag&drop operation.
The first time I drag or click the sprites everything works fine, but when I try to drag them again after the effect has been played once they won't drop. I can see the sprites move along with the mouse cursor as i drag them, but when I release the mouse button the sprites jump back to their starting position instead of dropping where I've just dragged them.
This happens only on individual sprites once the effect has been played on them a first time. After that the effect still plays each time (meaning that the MOUSE_UP event is dispatched), but they won't drop.
I'm also tracking the coordinates of the sprites as they are dragged, using a label I update through the MOUSE_MOVE event. The sprites' coordinates update normally the first time I drag&drop them, but then, after the effect is played for the first time, the coordinates won't update either.
This only happens with effects that affect the sprites' appearance: s:Animate (scaleX, scaleY), s:Rotate, s:Scale.
The only one that seems to work without causing any problem is s:Move. Don't understand why.
Does anyone have any idea?
Thanks a lotOh, I see. Thanks.
So... i should use the "normal" flex drag&drop.
There is just a problem, the documentation says:
The following Flex features are not supported in mobile applications:
No support for drag-and-drop operations
http://help.adobe.com/en_US/flex/mobileapps/WSf3db6597adcd110e19124fcb12ab3a1c319-8000.htm l#WSca1097f1363f276f-8bfd51512ba1a8112c-8000
I had to work my way around this limitation one time in the past. I assumed that those lines referred to list-based controls only and I figured that maybe I could manually implement drag&drop with my custom components, which I did. It worked quite well, but unfortunately it also made the mouse cursor appear beneath my fingertip. It was very annoying and I couldn't find a way to get rid of it.
I also thought about implementing the "flex" drag&drop using TouchEvents instead of MouseEvents (maybe that was the cause of the problem, I thought), but the DragManager.doDrag() method requires a MouseEvent as argument.... and that's when I decided to switch to the more basic .startTouchDrag() and stopTouchDrag() methods.
Now, is there something else I could try?
How do other people (more experienced than me) implement their drag&drop mechanics, for starters?
Thank you :-) -
Mapping/invoking key codes in a GameCanvas's main game loop.
I'm trying to bind some diagonal sprite movement methods to the keypad. I already know that I have to map out the diagonals to key codes since key states only look out for key presses in the upper half of the phone (d-pad, soft buttons, etc...). Problem is, how do I invoke them in the main game loop since a key state can be encapsulated in a method and piped through the loop? What makes this even worst is a bug that my phone maker's game API (Siemens Game API for MIDP 1.0, which is their own implementation of the MIDP 2.0 Game API) has, in which if I override the keyPressed, keyReleased, or keyRepeated methods, it will always set my key states to zero, thus I can't move the sprite at all. Also, it seems that my phone's emulator automatically maps key states to 2, 4, 6, and 8, so my only concern is how do I map the diagonal methods into 1, 3, 7, and 9, as well as invoking them in the main game loop? Enclosed is the example code that I've been working on as well as the link to a thread in the Siemens (now Benq Mobile) developer's forum about the bug's discovery:
http://agathonisi.erlm.siemens.de:8080/jive3/thread.jspa?forumID=6&threadID=15784&messageID=57992#57992
the code:
import com.siemens.mp.color_game.*;
import javax.microedition.lcdui.*;
public class ExampleGameCanvas extends GameCanvas implements Runnable {
private boolean isPlay; // Game Loop runs when isPlay is true
private long delay; // To give thread consistency
private int currentX, currentY; // To hold current position of the 'X'
private int width; // To hold screen width
private int height; // To hold screen height
// Sprites to be used
private GreenThing playerSprite;
private Sprite backgroundSprite;
// Layer Manager
private LayerManager layerManager;
// Constructor and initialization
public ExampleGameCanvas() throws Exception {
super(true);
width = getWidth();
height = getHeight();
currentX = width / 2;
currentY = height / 2;
delay = 20;
// Load Images to Sprites
Image playerImage = Image.createImage("/transparent.PNG");
playerSprite = new GreenThing (playerImage,32,32,width,height);
playerSprite.startPosition();
Image backgroundImage = Image.createImage("/background2.PNG");
backgroundSprite = new Sprite(backgroundImage);
layerManager = new LayerManager();
layerManager.append(playerSprite);
layerManager.append(backgroundSprite);
// Automatically start thread for game loop
public void start() {
isPlay = true;
Thread t = new Thread(this);
t.start();
public void stop() { isPlay = false; }
// Main Game Loop
public void run() {
Graphics g = getGraphics();
while (isPlay == true) {
input();
drawScreen(g);
try { Thread.sleep(delay); }
catch (InterruptedException ie) {}
//diagonalInput(diagonalGameAction);
// Method to Handle User Inputs
private void input() {
int keyStates = getKeyStates();
//playerSprite.setFrame(0);
// Left
if ((keyStates & LEFT_PRESSED) != 0) {
playerSprite.moveLeft();
// Right
if ((keyStates & RIGHT_PRESSED) !=0 ) {
playerSprite.moveRight();
// Up
if ((keyStates & UP_PRESSED) != 0) {
playerSprite.moveUp();
// Down
if ((keyStates & DOWN_PRESSED) !=0) {
playerSprite.moveDown();
/*private void diagonalInput(int gameAction){
//Up-left
if (gameAction==KEY_NUM1){
playerSprite.moveUpLeft();
//Up-Right
if (gameAction==KEY_NUM3){
playerSprite.moveUpRight();
//Down-Left
if (gameAction==KEY_NUM7){
playerSprite.moveDownLeft();
//Down-Right
if (gameAction==KEY_NUM9){
playerSprite.moveDownRight();
/*protected void keyPressed(int keyCode){
int diagonalGameAction = getGameAction(keyCode);
switch (diagonalGameAction)
case GameCanvas.KEY_NUM1:
if ((diagonalGameAction & KEY_NUM1) !=0)
playerSprite.moveUpLeft();
break;
case GameCanvas.KEY_NUM3:
if ((diagonalGameAction & KEY_NUM3) !=0)
playerSprite.moveUpRight();
break;
case GameCanvas.KEY_NUM7:
if ((diagonalGameAction & KEY_NUM7) !=0)
playerSprite.moveDownLeft();
break;
case GameCanvas.KEY_NUM9:
if ((diagonalGameAction & KEY_NUM9) !=0)
playerSprite.moveDownRight();
break;
repaint();
// Method to Display Graphics
private void drawScreen(Graphics g) {
//g.setColor(0x00C000);
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x0000ff);
// updating player sprite position
//playerSprite.setPosition(currentX,currentY);
// display all layers
//layerManager.paint(g,0,0);
layerManager.setViewWindow(0,0,101,80);
layerManager.paint(g,0,0);
flushGraphics();
}EDIT: Also enclosed is a thread over in J2ME.org in which another user reports of the same flaw.
http://www.j2me.org/yabbse/index.php?board=12;action=display;threadid=5068Okay...you lost me...I thought that's what I was doing?
If you mean try hitTestPoint ala this:
wally2.addEventListener(Event.ENTER_FRAME, letsSee);
function letsSee(event:Event)
// create a for loop to test each array item hitting wally...
for (var i:Number=0; i<iceiceArray.length; i++)
// if you don't hit platform...
if (wally2.hitTestPoint(iceiceArray[i].x, iceiceArray[i].y, false)) {
wally2.y -= 5;}
return;
That's not working either. -
An animated gif which dasnt refreshed..
Hi all !
First let me apologize for my bad english.
Secondly, I tried to show on the screen transpaernt animated gif, in another words, sprite(character) which walk on the desktop, well, i succsed, but there is a problem, if the sprite move is head, the on the screen you will see the sprite before and after the movmenet, there is a trail.
i hope that you could help me.
my code is very simple at this moment:
public class WS extends JWindow
Image img=null;
Image img2=null;
Toolkit tk=null;
public WS()
tk=Toolkit.getDefaultToolkit();
this.setSize(500, 500);
this.setLocation(500, 500);
img2=tk.getImage("MijalNo.gif");
this.prepareImage(img2, null);
this.setVisible(true);
public void paint(Graphics g)
g.drawImage(img2, 0, 0, this);
}thank you.For those who doenst understand my problem, the here is the printscreen:
http://members.lycos.co.uk/ofir3dvb2/theprob.JPG
Edited by: ofir3dvb on Mar 16, 2008 5:08 AM
Maybe you are looking for
-
Update failed. Windows - Creative Suite 5 Premium. Trying to update Camera Raw.
My apologies if I'm not following the correct protocol on this forum. It's my first time here. I'm a novice with Photoshop and the Creative Suite, and until now I have only used its basic features. However, I tried to upload a RAW format image today,
-
BPM : Files are not appended in the container operation step
Hi Guys, I am using the BPM pattern, "BpmPatternCollectTime" provided by the SAP under SAP BASIS 6.4 for the N:1 transformation. In the the Message mapping and Interface mapping source structure has "0 to unbounded" occurance and Target has 1 coo
-
Hi guys, I am studying about Java Server Pages, I lear that the jsp:plugin tag of JSP techcnology have support for this. Then I create a simple swing applet and a JSP page like fellow: <jsp:plugin type="applet" code="package.MyApplet" width="450" hei
-
Substitute an Icon in URL field
How can I change an http://alt-web.com/favicons.shtml selected icon into another favicon? I think I have to use the a analogous commandline as "image/vnd.microsoft.icon". Does somebody know the analogous "favicon-term"? Thanks for efforts just yet. C
-
My requirement is to get a file from SFTP server & place it in NFS/Al11 (ECC). Once I place the file call an RFC enabled Function module. No mapping is involved. My question is how can I call RFC from PI without mapping. I have verified RFC parameter