P. Sha
P. Sha

Reputation: 11

Java Graphics2D only drawing if rotated 0/360 degrees

I tried to make a rotated enemy that simply moves forward. The player shows perfectly, but for some reason the enemy only shows if I set the rotation to 360 or 0, even though the x and y positions move as they should.

package Game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Enemy extends Rectangle implements GameObject {

    private int speed;
    private double angle;

    public Enemy(int x, int y, int w, int h, int speed, int angle) {
        this.x = x;
        this.y = y;
        this.width = w;
        this.height = h;
        this.speed = speed;
        this.angle = Math.toRadians(angle);
    }

    @Override
    public void update(Engine g) {
        this.x += (speed * (float) Math.cos(angle));
        this.y += (speed * (float) Math.sin(angle));

        System.out.println(this.x + " " + this.y);
    }

    @Override
    public void render(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.red);
        g2d.rotate(angle);
        g2d.fill(this);
    }

}

Upvotes: 0

Views: 106

Answers (1)

Kennedy
Kennedy

Reputation: 557

Change your render component to this

@Override
public void render(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.red);
    g2d.rotate(this.angle);
    g2d.fill(this);
    g2d.draw(this);
    this.render(g);
}

Upvotes: 1

Related Questions