Rotating and Translating an Image

I am making a game with a tank that can rotate and move forwards and backwards.
I am able to get the tank Image to rotate, but when I call a translation, it resets the image back to its original image. How can I fix this?

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class TankGame extends JPanel {
    Walker walker = new Walker(this);
    BufferedImage image;
    AffineTransform at = new AffineTransform();
    Point2D.Double loc = new Point2D.Double(200,150);
    double theta = 0;
    double t = 3.0;
    boolean goAhead = true;
    public TankGame(BufferedImage image) {
        this.image = image;
        setTransform();
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.drawRenderedImage(image, at);
        //g2.setPaint(Color.red);
        //g2.fill(new Ellipse2D.Double(loc.x-2, loc.y-2, 4, 4));
    public synchronized void step() {
        int sign = goAhead ? 1 : -1;
        double x = loc.x + sign*t*Math.cos(theta);
        double y = loc.y + sign*t*Math.sin(theta);
        loc.setLocation(x, y);
        setTransform();
        repaint();
    private void setTransform() {
        double x = loc.x - image.getWidth()/2;
        double y = loc.y - image.getHeight()/2;
        at.setToTranslation(x, y);
        at.rotate(theta, image.getWidth()/2, image.getHeight()/2);
    private JPanel getUIPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(1,0,1,0);
        gbc.weightx = 1.0;
        String[] ids = { "ahead", "stop", "back" };
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String ac = e.getActionCommand();
                if(ac.equals("stop")) {
                    walker.stop();
                } else {
                    if(ac.equals("ahead")) {
                        goAhead = true;
                    } else if(ac.equals("back")) {
                        goAhead = false;
                    walker.start();
        for(int j = 0; j < ids.length; j++) {
            JButton button = new JButton(ids[j]);
            button.addActionListener(al);
            if(j == ids.length-1)
                gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(button, gbc);
        JSlider slider = new JSlider(-180, 180, 0);
        slider.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                int angle = ((JSlider)e.getSource()).getValue();
                theta = Math.toRadians(angle);
                setTransform();
                repaint();
        gbc.gridwidth = 3;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel.add(slider, gbc);
        return panel;
    public static void main(String[] args) throws IOException {
        String path = "images/geek/geek----t.gif";
        BufferedImage image = ImageIO.read(new File(path));
        TankGame test = new TankGame(image);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(test);
        f.add(test.getUIPanel(), "Last");
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class Walker implements Runnable {
    TankGame game;
    Thread thread;
    boolean moving = false;
    long delay = 100;
    public Walker(TankGame tg) {
        game = tg;
    public void run() {
        while(moving) {
            try {
                Thread.sleep(delay);
            } catch(InterruptedException e) {
                moving = false;
            game.step();
    public void start() {
        if(!moving) {
            moving = true;
            thread = new Thread(this);
            thread.setPriority(Thread.NORM_PRIORITY);
            thread.start();
    public void stop() {
        moving = false;
        if(thread != null)
            thread.interrupt();
        thread = null;
}

Similar Messages

  • How to rotate and translate an object at the same time??

    Hi, I have a problem with rotation and translation of an object at the same time. I wrote a behovior class for my object (a cylinder). When some conditions are true the cylinder is added to a robot arm. Then it is translated so that the cylinder would be very close to the arm (looks like the robot is holding it). And now the behavior should also rotate the cylinder because the angle is 0 and it should be 90. I can translate the object or I can rotate the object but when I'm trying to do it at the same time (I want to combine rotation and translation) it doesn't work.
    Could anyone help me, please :)

    You can used to Matrix3f
    This object is a rotation and translate matrix
    for example:
    private void componerTransformada(){
    Quat4f rot = new Quat4f((float) this.getRotacionSobreX(),(float) this.getRotacionSobreY(),
    (float) this.getRotacionSobreZ(),1.0f);
    Vector3f tras = new Vector3f(-4.0f,-4.0f,(-1)*this.getDistanciaDeLaCamara());
    this.setTransformacion(new Transform3D(new Matrix4f(rot, tras, 1.0f)));
    Quat4f is a matrix of ratation
    vector3f is a direction vector
    Transform3d is building with Quat4f and Vector3f.
    That is work i use this to situe the view of point.
    good locky

  • Rotate and scale an image witohout deforming it

    Hello you all!
    I have to rotate and scale an image, but i don't wont to deform it.
    I'm thinking to something like 16/9 images on 4/3 screens (with two horizontal or vertical black lines around the scaled image)...
    I thinked to transform the image in bitmap format, then create a bigger image and fill the empty spaces with zero-pixels...
    Is there a simplest and more efficient way to do it with 2D java classes?
    Thank you!

    See reply 8 in Help to rotate image for an idea.

  • Is it possible to rotate and scale an image?

    Is it possible to rotate and scale an image with Grapchis2D at the same time?
    One method call to do it all?
    lets say the original image size is 200x200
    I can scale the image with
    Graphics.drawImage(image, 0,0, 500,500,this);
    But now i need to rotate it as well and keep the new size which is 500x500
    how do i do that ?

    Have you already tried the scale(double sx, double
    sy) and rotate(double theta) methods of Graphics2D?no.

  • Problem with very slow scale, rotate and translate

    Hi -
    Here is the basic problem. I want to take a bufferedImage (read from a jpeg earlier on) and then rotate it according to an angle value (radians) and then resize it to fit within a specifically sized box. My code works fine, but... I have to do this in a loop up to 200 times. The process is often taking several minutes to complete. If this is simply a consequence of what I am trying to do, then I'll accept that, but surely I am just doing something wrong? Please help!
    Thanks - here is the (working but very slow) code
        public Graphics2D get_shape_image(Graphics2D g, BufferedImage b, double shaperotation, double space_width, double space_height,
                float x_scale_factor, float y_scale_factor, float shapeTransparency){
            // Work out the boundimg box size of the rotated image
            double imageWidth = (double) b.getWidth();
            double imageHeight = (double) b.getHeight();
            double cos = Math.abs( Math.cos(shaperotation));
            double sin = Math.abs( Math.sin(shaperotation));
            int new_width = (int) Math.floor(imageWidth * cos  +  imageHeight * sin);
            int new_height = (int) Math.floor(imageHeight * cos  +  imageWidth * sin);
            // Create the new bufferedImage of the right size
            BufferedImage transformed = new BufferedImage((int) new_width, (int) new_height, BufferedImage.TYPE_INT_RGB);
            // Create the transform and associated AffineTransformOperation
            AffineTransform at = new AffineTransform();
            AffineTransformOp affine_op;
            // Make sure our image to be rotated is in the middle of the new image
            double x_movement = ((double) (new_width / 2.0d)) - ((double) imageWidth / 2.0d);
            double y_movement = ((double) (new_height / 2.0d)) - ((double) imageHeight / 2.0d);
            at.setToTranslation(x_movement, y_movement);
            affine_op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            transformed = affine_op.filter(b, null);
            // Now we need to rotate the image according to the input rotation angle
            BufferedImage rotated = new BufferedImage((int) new_width, (int) new_height, BufferedImage.TYPE_INT_RGB);
            at.setToRotation(shaperotation, (double) new_width / 2.0d, new_height / 2.0d);
            affine_op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            rotated = affine_op.filter(transformed, null);
            // Do the scaling so that we fit into the grid sizes
            BufferedImage sizedImage = new BufferedImage((int) (space_width * x_scale_factor), (int) (space_height * y_scale_factor), BufferedImage.TYPE_INT_RGB);
            double xScale = (double) (space_width * x_scale_factor) / (double) new_width;
            double yScale = (double) (space_height * y_scale_factor) / (double) new_height;
            at.setToScale(xScale, yScale);
            affine_op = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            sizedImage = affine_op.filter(rotated, null);
            // Finally translate the image to the correct position after scaling
            double x_adjust = (space_width / 2.0d) - ((space_width * x_scale_factor) / 2.0d);
            double y_adjust = (space_height / 2.0d) - ((space_height * y_scale_factor) / 2.0d);
            // Set the transparency
            AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, shapeTransparency);
            g.setComposite(ac);
            // Draw the image as long as it's above 0 size
            if (sizedImage.getWidth() > 0 && sizedImage.getHeight() > 0)
                g.drawImage(sizedImage, null, (int) x_adjust, (int) y_adjust);
            return g;
        }

    Your code worked okay in my system: busy at 200fps using 1.0f for alpha and
    the x/y scale_factor values.
    Here's another approach that isn't quite as busy.
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class XTest extends JPanel
        BufferedImage image;
        int gridWidth  = 100;
        int gridHeight = 100;
        double theta   = 0;
        double thetaInc;
        public XTest(BufferedImage image)
            this.image = image;
            thetaInc = Math.toRadians(1);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            int w = getWidth();
            int h = getHeight();
            int imageW = image.getWidth();
            int imageH = image.getHeight();
            // rather than making a new BufferedImage for each step of
            // the rotation and scaling let's try to rotate, scale and
            // fit the source image directly into the grid by using
            // transforms...
            // rotation
            AffineTransform rotateXform = new AffineTransform();
            double x = (w - imageW)/2;
            double y = (h - imageH)/2;
            rotateXform.setToTranslation(x,y);
            rotateXform.rotate(theta, imageW/2.0, imageH/2.0);
            // get rotated size for source
            double cos = Math.abs( Math.cos(theta));
            double sin = Math.abs( Math.sin(theta));
            double rw = Math.rint(imageW * cos  +  imageH * sin);
            double rh = Math.rint(imageH * cos  +  imageW * sin);
            // scale factors to fit image into grid
            double xScale = gridWidth /  rw;
            double yScale = gridHeight / rh;
            // scale from center
            x = (1.0 - xScale)*w/2;
            y = (1.0 - yScale)*h/2;
            AffineTransform scaleXform = AffineTransform.getTranslateInstance(x,y);
            scaleXform.scale(xScale, yScale);
            scaleXform.concatenate(rotateXform);
            g2.drawRenderedImage(image, scaleXform);
            // markers
            // grid
            g2.setPaint(Color.red);
            int gx = (w - gridWidth)/2;
            int gy = (h - gridHeight)/2;
            g2.drawRect(gx, gy, gridWidth, gridHeight);
            // bounds of unscaled, rotated source image
            g2.setPaint(Color.blue);
            double rx = (w - rw)/2;
            double ry = (h - rh)/2;
            g2.draw(new Rectangle2D.Double(rx, ry, rw, rh));
        public void rotate()
            theta += thetaInc;
            repaint();
        public static void main(String[] args) throws IOException
            BufferedImage bi = ImageIO.read(new File("images/bclynx.jpg"));
            XTest test = new XTest(bi);
            Activator activator = new Activator(test);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            activator.start();
    class Activator implements Runnable
        XTest xTest;
        Thread thread;
        boolean animate;
        public Activator(XTest xt)
            xTest = xt;
            animate = false;
        public void run()
            while(animate)
                try
                    Thread.sleep(50);
                catch(InterruptedException ie)
                    animate = false;
                    System.out.println("interrupt");
                xTest.rotate();
        public void start()
            if(!animate)
                animate = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
        public void stop()
            animate = false;
            thread = null;
    }

  • Combing rotate and translation?

    hey
    i want to both rotate and set a translation on a ColorCube, but i cant to them to work at the same time.
    In the code i have it works fine if i use either the rotate code OR the translation code, if i put in the code for both, it only rotates on the x axis, eventho it also rotates on y-axis with translation code, and it doesnt rotate as much as if i leave the translation part out.
    Why is that?
    Here is the code:
    public void createPhyBox(){
            // Position box in scene
            Transform3D t3d = new Transform3D();
            t3d.setTranslation( new Vector3d(-0.4f, 0.0f, 0.0f));
            // Rotate box
            Transform3D rotate = new Transform3D();
            Transform3D tempRotate = new Transform3D();
            rotate.rotX(Math.PI/3.0d);
            tempRotate.rotY(Math.PI/5.0d);
            rotate.mul(tempRotate);
            baseTG = new TransformGroup(rotate);
            baseTG.setTransform(t3d);
            baseTG.addChild(new ColorCube(0.2));
        }

    i helped myself :D

  • Rotating and cropping an image.

    I am taking a Photoshop for school and we are using CS5. I have CS6 and I'm stuck on my picture rotating back straight when I am trying to crop it.  I use the rotate view and rotate it 6degrees. As soon as I hit the crop button the picture goes straight. How can I keep my picture rotated to the 6degrees and crop it without the perspective crop tool?

    Rotate view only rotates...  the view; not the actual picture.  It's temporary and non-destructive. It's used to help move the canvas to a better angle for drawing brush strokes.
    You want to actually rotate the image or canvas.  Either Ctrl T for Free Transform and rotate by moving the cursor outside one of the corners and dragging.  Or Edit > Transform > Rotate

  • Rotate and save an image

    Hi All,
    I am a new comer. Could I ask you a question about java 2D? I want to rotate an image and then save it as another file, but now I don't know how to make the rotated iamge as a new one so that I can save it. Could you give me some ideas?
    Thanks,
    Regards,

    look up the Affine Transforms or use JAI.

  • Rotating and dragging of image using mouse

    hi everyone,
    I've got problems with dragging and rotating of images using the mouse
    Can anyone show me how to that?
    Thanks a million

    Implement a MouseMotionListener on the Panel that you want to drag the image on.
    public void mouseDragged  (   MouseEvent e   )
           if ( e.getModifiers() == MouseEvent.BUTTON1_MASK )
              if ( dragged )
                  processMove( new Point2D.Double( e.getPoint().x, e.getPoint().y ) );
             else
               wasDragged = true;
                  dragged    = true;
                  dragPoint  = new Point2D.Double( e.getPoint().x, e.getPoint().y );
                  xDiff      = 0;
                  yDiff      = 0;
    private void processMove
         Point2D.Double    point
              Point2D.Double paintPoint = new Point2D.Double( point.x - dragPoint.x, point.y - dragPoint.y );
           BufferedImage  imageBak   = getCurrentBackgroundImage();
           BufferedImage  background = new BufferedImage( imageBak.getWidth(), imageBak.getHeight(), imageBak.getType() );
           Graphics2D     gr         = background.createGraphics();
           gr.setColor( adaptee.getUserProfile().getBackgroundColor() );
           gr.fillRect( 0, 0, imageBak.getWidth(), imageBak.getHeight() );
           gr.drawImage( imageBak, null, (int) paintPoint.x, (int) paintPoint.y );
              gr.finalize();
           xDiff += paintPoint.x;
           yDiff += paintPoint.y;
           dragPoint = point;
           getGraphicsForPanelToDrawOn()..drawImage( background, null, 0, 0 );       
           setCurrentBackgroundImage(  background );
              }

  • Rotating and saving an image

    Hi, i'm trying to rotate an image and then save the rotated image to the hard drive in jpeg format. I've managed to get the rotation part working, but i can't seem to save the image correctly.

    Here is some code. You'll need to catch exceptions etc.
    BufferedImage expImage = new BufferedImage( (int)component.getWidth(), (int)component.getHeight(), BufferedImage.TYPE_INT_RGB );
                   Graphics g2d = expImage.getGraphics();
                   draftGrid.update(g2d);
                   layoutGrid.update(g2d);
                   g2d.dispose();
                        fileName = verifyFileName(fileName, "jpeg");
                        OutputStream out = new FileOutputStream( fileName );
                        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                        encoder.encode(expImage);
                        out.flush();
                        out.close();
                        expImage.flush();
    /** This draft has been saved to fileName **/

  • Rotating and Translating Objects with Collision Modifiers

    Hello
    Im trying to build a simple 3d scene. The idea being that a
    footballer walks up to a football and on detection of that
    collision, the football is translated or 'kicked.'
    Got the Collision Detection working using Collision
    Modifiers. Got it working so that it registers the collisions, what
    I havent gotten is how to translate the object (football) I have
    used the simple translate command but this seems to work on objects
    without collision modifiers.
    Does anyone have any work arounds?
    Thanks in Advance

    Hello
    Im trying to build a simple 3d scene. The idea being that a
    footballer walks up to a football and on detection of that
    collision, the football is translated or 'kicked.'
    Got the Collision Detection working using Collision
    Modifiers. Got it working so that it registers the collisions, what
    I havent gotten is how to translate the object (football) I have
    used the simple translate command but this seems to work on objects
    without collision modifiers.
    Does anyone have any work arounds?
    Thanks in Advance

  • Rotate and move image

    Hi,I'm trying to make a game kinda like gta or asteroids whereyou have top view. I am using an image to be the player and, I want to rotate that image using left and righ keys and with the up key move the player to the direction whereit is rotated.
    The problem is that i cannot display the rotation and movement at the same time.
    I'm using a code like this.
    AffineTransform transform = new AffineTransform
    public void checkGameInput(){
         float velocityX=0;
         float velocityY=0;
         if(rotateLeft.isPressed()){
               angle1+=angle2;    
              transform.rotate(-angle2, player.getWidth()/2, player.getHeight()/2);
    // similar for rightkey
       if (moveFront.isPressed()){
               velocityX=_Player.SPEED*Math.cos(angle1),
               //same for velocityY
    }the problem is when i try to print on the sceen.
    I can update position
    public void draw(Graphics 2D g){
    g.drawImage(player. getImage(), Math.round(player.getX()), Math.round(player.getY()),null)  // player.getX(9 returns position of playeror update rtation
    public void draw(Graphics 2D g){
    g.drawImage(player.getImage(),transform, null);is there a way to join this to drawImageso I can rotate ane move the rotatyed image?
    thank you very much for any kind of help.
    Edited by: Muninn on Nov 29, 2008 3:13 AM

    Use the transform to do both rotation and translation (multiple transform operations can be concatenated)
    transform.rotate(-angle2, player.getWidth()/2, player.getHeight()/2);
    transform.translate(player.getX(), player.getY());

  • Performance issues with Motion (position, scale, rotate) and GTX 590

    I'm experiencing performance issues with my Premiere Pro CC when I scale, position or rotate a clip in the program monitor.
    I have no performance issues with playback! It's only, when i move something with the mouse or by changing the x,y-values of Position in the Motion-Dialog in video effects.
    Premiere then lags terribly and updates the program monitor only about once per second - this makes it very difficult and cumbersome to work and position things.
    On a second Premiere installation on my laptop, performance is fine and fluid - allthough it doesn't have GPU support and is a much slower computer.
    I'm pretty sure this has somehow to do with my graphic card, which is a Nvidia GTX 590.
    I was told by the support, that it is actually a dual graphic card, which is not supported/liked by Premiere.
    The thing is, until the latest Premiere update, I did not have performance issues at all with this card.
    I also read on the forum that others with the GTX 590 did not experience any problems with it
    So where does this come from?
    There is no change in performance whether or not I activate Mercury Playback Engine GPU acceleration.
    I also tried deactivating one of the 2 gpus, but there also was no change.
    Does anyone else know this problem and has anyone a solution?
    I'm running Premiere CC on a Win 7 64bit engine, Nvidia GTX 590, latest driver (of today),

    I am suffering from the same phenomenon since I updated just before christmas, I think.
    I am hardly able to do scaling, rotating and translating in the program monitor itslef - whil motion has been highlighted in teh effect controls.
    In the effect controls I can scale, rotate etc however.
    Also I have noticed there is a yellow box with handles in teh program monitor. I remember it was white before.
    I cannot figure out what to change in my preferences. What has happened?
    best,
    Hans Wessels
    Premiere CC
    Mac Pro OSX 10.7.5
    16 GB 1066 MHz DD3
    2 X NVIDIA GeForce GT 120 512 MB

  • How Can I Rotate and Zoom?

    Let's say I have a circle that's a large, detailed image. I want to be able to rotate and zoom to different points on that circle. How can that be accomplished in Muse? Thanks!

    What you want to do isn't possible with just Muse if I understand what you are trying to do correctly. I am assuming you want the user to be able to rotate and zoom the image?
    If so, then Edge Animate would be the tool you need and then import that into your Muse project.

  • Images rotate and resize when relinking after collect for output

    I just started using CS5 and have run into an issue that is very disturbing to me. When I relink my files from the collected folder that I send to printer, images that have been rotated in Indesign rotate to their actual size and rotation. This is not a good thing! We should not have to rotate all of our images outside of indesign.. Please Help!!!

    OK, we were cross posting, and I've now looked at your file.
    One key piece of information you didn't tell us before is that the file was created in CS3 and converted. There are a lot of reports of strange behavior with legacy files. This one seems to be somewhat corrupt at this point. I don't know how much of that was introduced form the conversion, and how much from the previous recycling.
    The best approach when converting a CS3 file is often to export as .inx from CS3 and open that in CS5. The other thing that helps is to open the old file iin CS5, then immediately export to .idml, then open that and save as a new .indd and work with that. Since I don't have the original CS3 version I don't know how that behaved or if .inx will help, but exporting this one to .idml seems to clear up problems with all the photos except the one at the top of page 4 which rotates 180 degrees when relinked.
    For best results you should probably rebuild this file from scratch in CS5, then save as a template. Starting each new editon from a template is more reliable than resaving an old issue and removing unwanted content. Although ID is more stable than most programs when you do this, creeping corruption is always a problem with long-term resaving of the same document and you often don't see it until you are hard up on deadline and your file goes south.

Maybe you are looking for

  • How to delete my iCloud using an old email no longer in use.

    I have an old AOL account that I no longer use.  I tried resetting the password but that didn't work.  So every time I go to delete the account it asks for my password which I do not know or not able to get anymore.  Does anyone know a way to delete

  • Answer - Why won't my Vision M play videos on my

    This may be the most technically illiterate post you'll read! But here goes.... After spending hours reading through posts?trying to find the answer to that question, I found it!?I had ordered and received the?cord with the white, yellow and red cabl

  • Questions about Macbook

    I am about to go into my first year of college this July, and I've been looking for a laptop. I've used iMacs before a little bit, but I have a few questions about the Macbook Pro and Mac OS X 10.5. So if someone can help me that would be great. Firs

  • ATG Promotion rule not working

    I have a requirement that if the order contains 3 specific products then apply $2 off on each of those products. I made an Order-Amount Off promotion something like the following, but it doesnt seem to work. [When order contains atleast 1 product nam

  • Bug on Calendar when going to march 2013

    When going to March 2013 on the Calendar app (view by month), it crashes...