- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何实现Actor重复并时时更新。0秒内,激光1处于初始位置。在 1 秒内已经有 2 个激光,其中 1 移动,第二个激光(新的激光取代了 0 秒内的 1)。在 3 秒内,1 已经移动到两个位置,第二个激光在 1 中占据了 1 个激光的位置最后第二、第三激光(0秒第一激光位置)
激光级
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class Laser extends BaseActor {
public Laser(float x, float y, Stage s) {
super(x, y, s);
loadTexture("assets/Line11.png");
setSize(30,10);
setMaxSpeed(800);
setBoundaryPolygon(8);
setSpeed(10);
}
public void act(float dt) {
super.act(dt);
applyPhysics(dt);
}
}
BaseActor 类
/**
* Extends functionality of the LibGDX Actor class.
* by adding support for textures/animation,
* collision polygons, movement, world boundaries, and camera scrolling.
* Most game objects should extend this class; lists of extensions can be retrieved by stage and
class name.
* @see #Actor
* @author Lee Stemkoski
*/
public class BaseActor extends Group
{
private Animation<TextureRegion> animation;
private float elapsedTime;
private boolean animationPaused;
private Vector2 velocityVec;
private Vector2 velocityVecY;
private Vector2 accelerationVec;
private float acceleration;
private float maxSpeed;
private float deceleration;
private Polygon boundaryPolygon;
// stores size of game world for all actors
private static Rectangle worldBounds;
public BaseActor(float x, float y, Stage s)
{
// call constructor from Actor class
super();
// perform additional initialization tasks
setPosition(x,y);
s.addActor(this);
// initialize animation data
animation = null;
elapsedTime = 0;
animationPaused = false;
// initialize physics data
velocityVec = new Vector2(0,0);
velocityVecY=new Vector2(0,0);
accelerationVec = new Vector2(0,0);
acceleration = 0;
maxSpeed = 1000;
deceleration = 0;
boundaryPolygon = null;
}
/**
* If this object moves completely past the world bounds,
* adjust its position to the opposite side of the world.
*/
public void wrapAroundWorld()
{
if (getX() + getWidth() < 0)
setX( worldBounds.width );
if (getX() > worldBounds.width)
setX( -getWidth());
if (getY() + getHeight() < 0)
setY( worldBounds.height );
if (getY() > worldBounds.height)
setY( -getHeight() );
}
/**
* Align center of actor at given position coordinates.
* @param x x-coordinate to center at
* @param y y-coordinate to center at
*/
public void centerAtPosition(float x, float y)
{
setPosition( x - getWidth()/2 , y - getHeight()/2 );
}
/**
* Repositions this BaseActor so its center is aligned
* with center of other BaseActor. Useful when one BaseActor spawns another.
* @param other BaseActor to align this BaseActor with
*/
public void centerAtActor(BaseActor other)
{
centerAtPosition( other.getX() + other.getWidth()/2 , other.getY() + other.getHeight()/2 );
}
// ----------------------------------------------
// Animation methods
// ----------------------------------------------
/**
* Sets the animation used when rendering this actor; also sets actor size.
* @param anim animation that will be drawn when actor is rendered
*/
public void setAnimation(Animation<TextureRegion> anim)
{
animation = anim;
TextureRegion tr = animation.getKeyFrame(0);
float w = tr.getRegionWidth();
float h = tr.getRegionHeight();
setSize( w, h );
setOrigin( w/2, h/2 );
if (boundaryPolygon == null)
setBoundaryRectangle();
}
/**
* Creates an animation from images stored in separate files.
* @param fileNames array of names of files containing animation images
* @param frameDuration how long each frame should be displayed
* @param loop should the animation loop
* @return animation created (useful for storing multiple animations)
*/
public Animation<TextureRegion> loadAnimationFromFiles(String[] fileNames, float frameDuration, boolean loop)
{
int fileCount = fileNames.length;
Array<TextureRegion> textureArray = new Array<TextureRegion>();
for (int n = 0; n < fileCount; n++)
{
String fileName = fileNames[n];
Texture texture = new Texture( Gdx.files.internal(fileName) );
texture.setFilter( TextureFilter.Linear, TextureFilter.Linear );
textureArray.add( new TextureRegion( texture ) );
}
Animation<TextureRegion> anim = new Animation<TextureRegion>(frameDuration, textureArray);
if (loop)
anim.setPlayMode(Animation.PlayMode.LOOP);
else
anim.setPlayMode(Animation.PlayMode.NORMAL);
if (animation == null)
setAnimation(anim);
return anim;
}
/**
* Creates an animation from a spritesheet: a rectangular grid of images stored in a single file.
* @param fileName name of file containing spritesheet
* @param rows number of rows of images in spritesheet
* @param cols number of columns of images in spritesheet
* @param frameDuration how long each frame should be displayed
* @param loop should the animation loop
* @return animation created (useful for storing multiple animations)
*/
public Animation<TextureRegion> loadAnimationFromSheet(String fileName, int rows, int cols, float frameDuration, boolean loop)
{
Texture texture = new Texture(Gdx.files.internal(fileName), true);
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
int frameWidth = texture.getWidth() / cols;
int frameHeight = texture.getHeight() / rows;
TextureRegion[][] temp = TextureRegion.split(texture, frameWidth, frameHeight);
Array<TextureRegion> textureArray = new Array<TextureRegion>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
textureArray.add( temp[r][c] );
Animation<TextureRegion> anim = new Animation<TextureRegion>(frameDuration, textureArray);
if (loop)
anim.setPlayMode(Animation.PlayMode.LOOP);
else
anim.setPlayMode(Animation.PlayMode.NORMAL);
if (animation == null)
setAnimation(anim);
return anim;
}
/**
* Convenience method for creating a 1-frame animation from a single texture.
* @param fileName names of image file
* @return animation created (useful for storing multiple animations)
*/
public Animation<TextureRegion> loadTexture(String fileName)
{
String[] fileNames = new String[1];
fileNames[0] = fileName;
return loadAnimationFromFiles(fileNames, 1, true);
}
/**
* Set the pause state of the animation.
* @param pause true to pause animation, false to resume animation
*/
public void setAnimationPaused(boolean pause)
{
animationPaused = pause;
}
/**
* Checks if animation is complete: if play mode is normal (not looping)
* and elapsed time is greater than time corresponding to last frame.
* @return
*/
public boolean isAnimationFinished()
{
return animation.isAnimationFinished(elapsedTime);
}
/**
* Sets the opacity of this actor.
* @param opacity value from 0 (transparent) to 1 (opaque)
*/
public void setOpacity(float opacity)
{
this.getColor().a = opacity;
}
// ----------------------------------------------
// physics/motion methods
// ----------------------------------------------
/**
* Set acceleration of this object.
* @param acc Acceleration in (pixels/second) per second.
*/
public void setAcceleration(float acc)
{
acceleration = acc;
}
/**
* Set deceleration of this object.
* Deceleration is only applied when object is not accelerating.
* @param dec Deceleration in (pixels/second) per second.
*/
public void setDeceleration(float dec)
{
deceleration = dec;
}
/**
* Set maximum speed of this object.
* @param ms Maximum speed of this object in (pixels/second).
*/
public void setMaxSpeed(float ms)
{
maxSpeed = ms;
}
/**
* Set the speed of movement (in pixels/second) in current direction.
* If current speed is zero (direction is undefined), direction will be set to 0 degrees.
* @param speed of movement (pixels/second)
*/
public void setSpeed(float speed)
{
// if length is zero, then assume motion angle is zero degrees
if (velocityVec.len() == 0)
velocityVec.set(speed, 0);
else
velocityVec.setLength(speed);
}
/**
* Calculates the speed of movement (in pixels/second).
* @return speed of movement (pixels/second)
*/
public float getSpeed()
{
return velocityVec.len();
}
/**
* Determines if this object is moving (if speed is greater than zero).
* @return false when speed is zero, true otherwise
*/
public boolean isMoving()
{
return (getSpeed() > 0);
}
/**
* Sets the angle of motion (in degrees).
* If current speed is zero, this will have no effect.
* @param angle of motion (degrees)
*/
public void setMotionAngle(float angle)
{
velocityVec.setAngle(angle);
}
/**
* Get the angle of motion (in degrees), calculated from the velocity vector.
* <br>
* To align actor image angle with motion angle, use <code>setRotation( getMotionAngle() )</code>.
* @return angle of motion (degrees)
*/
public float getMotionAngle()
{
return velocityVec.angle();
}
/**
* Update accelerate vector by angle and value stored in acceleration field.
* Acceleration is applied by <code>applyPhysics</code> method.
* @param angle Angle (degrees) in which to accelerate.
* @see #acceleration
* @see #applyPhysics
*/
public void accelerateAtAngle(float angle)
{
accelerationVec.add(
new Vector2(acceleration, 0).setAngle(angle) );
}
/**
* Update accelerate vector by current rotation angle and value stored in acceleration field.
* Acceleration is applied by <code>applyPhysics</code> method.
* @see #acceleration
* @see #applyPhysics
*/
public void accelerateForward()
{
accelerateAtAngle( getRotation() );
}
/**
* Adjust velocity vector based on acceleration vector,
* then adjust position based on velocity vector. <br>
* If not accelerating, deceleration value is applied. <br>
* Speed is limited by maxSpeed value. <br>
* Acceleration vector reset to (0,0) at end of method. <br>
* @param dt Time elapsed since previous frame (delta time); typically obtained from <code>act</code> method.
* @see #acceleration
* @see #deceleration
* @see #maxSpeed
*/
public void applyPhysics(float dt)
{
// apply acceleration
velocityVec.add( accelerationVec.x * dt, accelerationVec.y * dt );
float speed = getSpeed();
// decrease speed (decelerate) when not accelerating
if (accelerationVec.len() == 0)
speed -= deceleration * dt;
// keep speed within set bounds
speed = MathUtils.clamp(speed, 0, maxSpeed);
// update velocity
setSpeed(speed);
// update position according to value stored in velocity vector
moveBy( velocityVec.x * dt, velocityVec.y * dt );
// reset acceleration
accelerationVec.set(0,0);
}
// ----------------------------------------------
// Collision polygon methods
// ----------------------------------------------
/**
* Set rectangular-shaped collision polygon.
* This method is automatically called when animation is set,
* provided that the current boundary polygon is null.
* @see #setAnimation
*/
public void setBoundaryRectangle()
{
float w = getWidth();
float h = getHeight();
float[] vertices = {0,0, w,0, w,h, 0,h};
boundaryPolygon = new Polygon(vertices);
}
/**
* Replace default (rectangle) collision polygon with an n-sided polygon. <br>
* Vertices of polygon lie on the ellipse contained within bounding rectangle.
* Note: one vertex will be located at point (0,width);
* a 4-sided polygon will appear in the orientation of a diamond.
* @param numSides number of sides of the collision polygon
*/
public void setBoundaryPolygon(int numSides)
{
float w = getWidth();
float h = getHeight();
float[] vertices = new float[2*numSides];
for (int i = 0; i < numSides; i++)
{
float angle = i * 6.28f / numSides;
// x-coordinate
vertices[2*i] = w/2 * MathUtils.cos(angle) + w/2;
// y-coordinate
vertices[2*i+1] = h/2 * MathUtils.sin(angle) + h/2;
}
boundaryPolygon = new Polygon(vertices);
}
/**
* Returns bounding polygon for this BaseActor, adjusted by Actor's current position and rotation.
* @return bounding polygon for this BaseActor
*/
public Polygon getBoundaryPolygon()
{
boundaryPolygon.setPosition( getX(), getY() );
boundaryPolygon.setOrigin( getOriginX(), getOriginY() );
boundaryPolygon.setRotation( getRotation() );
boundaryPolygon.setScale( getScaleX(), getScaleY() );
return boundaryPolygon;
}
/**
* Determine if this BaseActor overlaps other BaseActor (according to collision polygons).
* @param other BaseActor to check for overlap
* @return true if collision polygons of this and other BaseActor overlap
* @see #setBoundaryRectangle
* @see #setBoundaryPolygon
*/
public boolean overlaps(BaseActor other)
{
Polygon poly1 = this.getBoundaryPolygon();
Polygon poly2 = other.getBoundaryPolygon();
// initial test to improve performance
if ( !poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()) )
return false;
return Intersector.overlapConvexPolygons( poly1, poly2 );
}
/**
* Implement a "solid"-like behavior:
* when there is overlap, move this BaseActor away from other BaseActor
* along minimum translation vector until there is no overlap.
* @param other BaseActor to check for overlap
* @return direction vector by which actor was translated, null if no overlap
*/
public Vector2 preventOverlap(BaseActor other)
{
Polygon poly1 = this.getBoundaryPolygon();
Polygon poly2 = other.getBoundaryPolygon();
// initial test to improve performance
if ( !poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()) )
return null;
MinimumTranslationVector mtv = new MinimumTranslationVector();
boolean polygonOverlap = Intersector.overlapConvexPolygons(poly1, poly2, mtv);
if ( !polygonOverlap )
return null;
this.moveBy( mtv.normal.x * mtv.depth, mtv.normal.y * mtv.depth );
return mtv.normal;
}
/**
* Determine if this BaseActor is near other BaseActor (according to collision polygons).
* @param distance amount (pixels) by which to enlarge collision polygon width and height
* @param other BaseActor to check if nearby
* @return true if collision polygons of this (enlarged) and other BaseActor overlap
* @see #setBoundaryRectangle
* @see #setBoundaryPolygon
*/
public boolean isWithinDistance(float distance, BaseActor other)
{
Polygon poly1 = this.getBoundaryPolygon();
float scaleX = (this.getWidth() + 2 * distance) / this.getWidth();
float scaleY = (this.getHeight() + 2 * distance) / this.getHeight();
poly1.setScale(scaleX, scaleY);
Polygon poly2 = other.getBoundaryPolygon();
// initial test to improve performance
if ( !poly1.getBoundingRectangle().overlaps(poly2.getBoundingRectangle()) )
return false;
return Intersector.overlapConvexPolygons( poly1, poly2 );
}
/**
* Set world dimensions for use by methods boundToWorld() and scrollTo().
* @param width width of world
* @param height height of world
*/
public static void setWorldBounds(float width, float height)
{
worldBounds = new Rectangle( 0,0, width, height );
}
/**
* Set world dimensions for use by methods boundToWorld() and scrollTo().
* // @param BaseActor whose size determines the world bounds (typically a background image)
*/
public static void setWorldBounds(BaseActor ba)
{
setWorldBounds( ba.getWidth(), ba.getHeight() );
}
/**
* Get world dimensions
* @return Rectangle whose width/height represent world bounds
*/
public static Rectangle getWorldBounds()
{
return worldBounds;
}
/**
* If an edge of an object moves past the world bounds,
* adjust its position to keep it completely on screen.
*/
public void boundToWorld()
{
if (getX() < 0)
setX(0);
if (getX() + getWidth() > worldBounds.width)
setX(worldBounds.width - getWidth());
if (getY() < 0)
setY(0);
if (getY() + getHeight() > worldBounds.height)
setY(worldBounds.height - getHeight());
}
/**
* Center camera on this object, while keeping camera's range of view
* (determined by screen size) completely within world bounds.
*/
public void alignCamera()
{
Camera cam = this.getStage().getCamera();
Viewport v = this.getStage().getViewport();
// center camera on actor
cam.position.set( this.getX() + this.getOriginX(), this.getY() + this.getOriginY(), 0 );
// bound camera to layout
cam.position.x = MathUtils.clamp(cam.position.x, cam.viewportWidth/2, worldBounds.width - cam.viewportWidth/2);
cam.position.y = MathUtils.clamp(cam.position.y, cam.viewportHeight/2, worldBounds.height - cam.viewportHeight/2);
cam.update();
}
// ----------------------------------------------
// Instance list methods
// ----------------------------------------------
/**
* Retrieves a list of all instances of the object from the given stage with the given class name
* or whose class extends the class with the given name.
* If no instances exist, returns an empty list.
* Useful when coding interactions between different types of game objects in update method.
* @param stage Stage containing BaseActor instances
* @param className name of a class that extends the BaseActor class
* @return list of instances of the object in stage which extend with the given class name
*/
public static ArrayList<BaseActor> getList(Stage stage, String className)
{
ArrayList<BaseActor> list = new ArrayList<BaseActor>();
Class theClass = null;
try
{ theClass = Class.forName(className); }
catch (Exception error)
{ error.printStackTrace(); }
for (Actor a : stage.getActors())
{
if ( theClass.isInstance( a ) )
list.add( (BaseActor)a );
}
return list;
}
/**
* Returns number of instances of a given class (that extends BaseActor).
* @param className name of a class that extends the BaseActor class
* @return number of instances of the class
*/
public static int count(Stage stage, String className)
{
return getList(stage, className).size();
}
// ----------------------------------------------
// Actor methods: act and draw
// ----------------------------------------------
/**
* Processes all Actions and related code for this object;
* automatically called by act method in Stage class.
* @param dt elapsed time (second) since last frame (supplied by Stage act method)
*/
public void act(float dt)
{
super.act( dt );
if (!animationPaused)
elapsedTime += dt;
}
/**
* Draws current frame of animation; automatically called by draw method in Stage class. <br>
* If color has been set, image will be tinted by that color. <br>
* If no animation has been set or object is invisible, nothing will be drawn.
* @param batch (supplied by Stage draw method)
* @param parentAlpha (supplied by Stage draw method)
* @see #setColor
* @see #setVisible
*
*/
public void draw(Batch batch, float parentAlpha)
{
// apply color tint effect
Color c = getColor();
batch.setColor(c.r, c.g, c.b, c.a);
if ( animation != null && isVisible() )
batch.draw( animation.getKeyFrame(elapsedTime),
getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation() );
super.draw( batch, parentAlpha );
}
}
我没有使用 BaseActor 类中的所有方法。我从书本上摘录了它,现在将其按原样用在我的工作中。
最佳答案
在不了解本类(class)的所有来龙去脉以及您正在使用的物理系统的情况下,我只能笼统地解释。您正在描述两件不同的事情:
第三件事(我假设)是激光应该在某个时刻消失,因为否则你将永远拥有不断增加的激光数量。
有两种不同的方法来实现第 1 点。
a.覆盖 act()
方法并从那里更新旋转。像这样的东西:
public void act(float delta){
super.act(delta);
setRotation(getRotation() + DEGREES_PER_SECOND * delta;
}
b.使用一系列操作。我不知道你希望它旋转多远,但是例如,你可以将其放入构造函数中:
addAction(Actions.rotateBy(270f, 3f, Interpolation.linear); // rotate 270 degrees in 3 seconds
对于第二个任务,您可以设置重复操作来执行该任务:
stage.addAction(Actions.repeat(Actions.run { new Runnable{
public void run() {
addActor(generateNewLaser());
}
));
其中generateNewLaser()
将创建新的Laser实例和关联的物理设置。以上是简化的。实际上,您可能希望保留对此操作的成员引用,以便您可以根据游戏中发生的情况取消它。
或者您可以在 render()
方法中手动处理逻辑,或者使用管理激光系统的其他类或其他方法。
关于java - 如何实现对象的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61601056/
我想知道如何考虑需要您做出某些选择才能看到最终结果的搜索系统。我说的是 select 表单,您可以在其中根据您的选择继续操作,然后您会看到结果。 下面描述了我正在谈论的一个随机示例。想象一下 Init
您好,我目前正在编写一些软件来管理我们的库存。我搜索了 2 个表 master_stock(保存每一个股票代码和描述)库存(保存库存代码、地点、数量...) 一切都很好,但这是我遇到的问题。 假设我的
我有 2 个表,我想合并其数据。id 是我的关键字段(增量且不同)。表1和表2字段说明例如:id - 名称 - 值 我想将表2的所有数据插入表1,它们有不同的数据,但在某些行中有相同的id。 所以当我
我正在努力解决汇编中的一个问题,我必须获取十六进制代码的第一个字节 (FF) 并将其复制到整个值中: 0x045893FF input 0xFFFFFFFF output 我所做的
我有 Eclipse Indigo 版本,我可以在其中运行 Java 和 C++ 项目。 但我只想使用另一个 Eclipse 来编写 C++ 项目。所以我将 eclipse(不是工作区)的源文件夹复制
This question already has answers here: What is a NullPointerException, and how do I fix it? (12个答案)
This question already has answers here: Numbering rows within groups in a data frame (8个答案) 5个月前关闭。
我知道用q记录到寄存器中,但我想知道是否可以设置一些东西来快速调用最后一个记录,就像一样。 回顾最后一个简短的编辑命令(有关 的讨论请参阅 here。)。 我知道@@,但它似乎只有在执行@z之后才起作
来自 Eclipse 并且一直习惯于复制行,发现 Xcode 没有这样的功能是很奇怪的。或者是吗? 我知道可以更改系统范围的键绑定(bind),但这不是我想要的。 最佳答案 要删除一行:Ctrl-A
假设我有一个包含元素的列表,例如[1,2,3,4,5,6,7,8]。我想创建长度为 N 的该元素的所有排列。 因此,对于N = 4,它将是[[1,1,1,1],[1,1,1,2],[1,1,2,1],
我有一个带有 JMenu 的 JFrame。当我在某些情况下添加包含图像的 JPanel 时,程序首次启动时菜单会重复。调整大小时重复的菜单消失。任何建议都非常感激。谢谢。代码如下: public c
我正在尝试查找目录中文件的重复项。 我对这个 block 有一个问题,它以文件地址作为参数: public void findFiles(ArrayList list){ HashMap hm
我知道这个问题已经发布并且已经给出了答案,但我的情况不同,因为我在单个方法上填充多个下拉列表,所以如果我点击此链接 After every postback dropdownlist items re
我正在尝试为我的日历应用程序实现重复模式。我希望它的工作方式与 Outlook 在您设置重复约会时的工作方式相同。 public async Task> ApplyReccurrencePeriod
我有一个利用 cookie 来支持准向导的应用程序(即,它是一组相互导航的页面,它们必须以特定顺序出现以进行注册)。 加载 Logon.aspx 页面时 - 默认页面 - 浏览器 cookie 看起来
我有 3 个输入,代码检查它们是否为空,如果为空,则将变量值添加到输入中。 所以我有 3 个具有值的变量: var input1text = "something here"; var input2t
根据数组的长度更改数组的每个元素的最佳方法是什么? 例如: User #1 input = "XYZVC" Expected Output = "BLABL" User #2 input = "XYZ
我在让 Algolia 正常工作时遇到了一些麻烦。我正在使用 NodeJS 并尝试在我的数据库和 Algolia 之间进行一些同步,但由于某种原因似乎随机弹出大量重复项。 如您所见,在某些情况下,会弹
遵循以下规则: expr: '(' expr ')' #exprExpr | expr ( AND expr )+ #exprAnd | expr ( OR expr )+ #exprO
我有一个布局,我想从左边进入并停留几秒钟,然后我希望它从右边离开。为此,我编写了以下代码: 这里我在布局中设置数据: private void loadDoctor(int doctorsInTheL
我是一名优秀的程序员,十分优秀!