gpt4 book ai didi

java - 可以更新其他对象值的动画类

转载 作者:行者123 更新时间:2023-12-02 06:04:00 25 4
gpt4 key购买 nike

我想要一个可以在不同项目中重用的动画类。问题是我如何让类更改另一个对象的成员(例如位置)。这是一个非常简化的版本,说明了它的操作方式和功能。

public class Animation() {

private float currValue, targetValue, duration;

public Animation(currValue, targetValue, duration) {
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
}

public void update() {
// Here I would update its currValue based on duration and target
}
}

所以当我想要制作动画时,假设我会做一个矩形的位置:

class Rectangle {

private float x, y;
private Animation a;

public Rectangle (x, y) {
this.x = x;
this.y = y;
this.a = new Animation(x, 100, 1000); // Duration in ms
}

public void update() {
a.update(); // Update animation
}
}

显然这不起作用,因为动画不会更新矩形的x值。我想到的只有一种解决方案,那就是传入 Rectangle 实例和字段名称“x”,然后使用 Reflection API 更新该值。但这似乎是一个非常糟糕的解决方案。

有什么建议吗?我应该以不同的方式设计我的代码吗?

最佳答案

在这种情况下,反射不一定是一个糟糕的解决方案。事实上,这是一个非常通用的解决方案,允许在客户端编写优雅的代码。但当然,人们应该了解使用反射的一般注意事项。

此类动画的一种非常务实的方法是“分解”动画实际执行的操作:即在您的情况下更改一些 float 值。因此,分离“客户端”代码和实现的一种方法可能如下:

interface FloatSetter {
void setFloat(float f);
}

public class Animation
{
private float currValue, targetValue, duration;
private FloatSetter floatSetter;

public Animation(
float currValue, float targetValue, float duration,
FloatSetter floatSetter)
{
this.currValue = currValue;
this.targetValue = targetValue;
this.duration = duration;
this.floatSetter = floatSetter;
}

public void update()
{
...
floatSetter.setFloat(currValue);
}
}

然后您可以将 FloatSetter 的适当实现传递给您的 Animation - 可能通过匿名内部类:

class Rectangle 
{
private float x, y;
private Animation a;

public Rectangle(float fx, float fy) {
this.x = fx;
this.y = fy;
FloatSetter floatSetter = new FloatSetter()
{
@Override
public void setFloat(float f)
{
this.x = f;
}
});
this.a = new Animation(x, 100, 1000, floatSetter);
}

public void update() {
a.update(); // Update animation
}
}

顺便说一句:根据您要实现的目标,我建议不要Animation 实例放入 Rectangle 中。但我认为这只是一个草图,以表明您的意图。

重要:您绝对应该查看“时序框架”:https://java.net/projects/timingframework 。这是 Chet Haase 和 Romain Guy 所著的《Filthy Rich Clients》(http://filthyrichclients.org/)一书中各章节的随附代码,他们当然知道自己的东西。该库非常非常复杂且灵活地实现了您显然想要在那里实现的目标。 (它们还支持使用反射( https://java.net/projects/timingframework/sources/svn/content/trunk/timingframework-core/src/main/java/org/jdesktop/core/animation/timing/PropertySetter.java?rev=423 )的通用“PropertySetter”,但这只是一个定义通用“TimingTarget”的辅助类,它是我上面概述的“FloatSetter”的复杂版本)。

关于java - 可以更新其他对象值的动画类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22437160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com