[英]How do I rotate an oval using Graphics2D and AffineTransform around an ever changing origin?
我正在制作自己的太空侵略者版本。 我在屏幕底部有一個射擊手,敵人從上面靠近。 我的射擊者可以沿着屏幕底部的x軸完美移動。 但是我必須給它一個炮塔,它可以根據按下的鍵繞射手的中心旋轉。
以x軸為0度旋轉(相對於y軸正旋轉角為正):
炮塔應始於射手頭部的頂部(即90度)。 如果按A
,則應繼續向左旋轉(逆時針),如果按D
,則應繼續向右旋轉(順時針)。 如果按S
它將停止旋轉。 允許最大旋轉180度(從正x軸到負x軸)。
到目前為止,使用代碼我的炮塔是從0度開始的(指向正x方向)。 如果按A
它將旋轉90度(垂直),如果按D
,將一直旋轉至-90度(垂直向下)。 如果我按S
它將停止。
我的問題是我必須在哪里進行更改以更正此輪換?
這是它應該開始的方式,它應該能夠一直向左和向右水平旋轉並在任一側停止:
感謝您的任何幫助!
編輯代碼:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
public class Turret{
private int omega; //rotation speed
private int width = 16;
private int height = 12;
private int currAngle;
private Player playa;
public Turret(Player p){
omega = 0;
playa = p;
currAngle = 0;
}
public void keyHasBeenPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_A){
omega = 1; //rotate anti-clockwise
}
if(key == KeyEvent.VK_D){
omega = -1; //rotate clockwise
}
if(key == KeyEvent.VK_S){
omega = 0;
}
}
public void rotate(){
//angle of rotation is between 90 (negative x-axis) and -90 ( positive x-axis)
if(currAngle + omega < 90 && currAngle + omega > -90){
currAngle += omega;
}
}
public void show(Graphics2D g2d){
g2d.setColor(Color.GREEN);
AffineTransform old = g2d.getTransform();
g2d.translate(playa.getCenterXcoord(),playa.getCenterYcoord());
g2d.rotate(Math.toRadians(-currAngle));
g2d.translate(-playa.getCenterXcoord(), -playa.getCenterYcoord());
g2d.fillOval(playa.getCenterXcoord() - width/2,
playa.getYcoord() - height/2, width, height);
g2d.setTransform(old);
}
public int getAngle() { return currAngle; }
}
我已將其固定,但某些角度對我而言仍然沒有意義。
假設您有來自組件或圖像的Graphics2D
:
- 獲取基礎(紅色)對象的中心:getX()+ getWidth()/ 2,getY()+ getHeight()/ 2;
- 做Graphics.translate(-xCenter,-YCenter);
- Graphics.rotate(炮塔旋轉);
- 現在已經旋轉了圖形對象,請向后平移:(getWidth()/ 2,getHeight()/ 2)
- 從步驟0繪制圖像
您也可以使用AffineTransform
進行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.