![](/img/trans.png)
[英]What's the best way to move a sprite faster than the update rate in a simple 2d game?
[英]What is the best way to move game objects, smoothly rather than teleporting it?
我正在尝试将游戏对象神奇宝贝从屏幕中心平滑移动到屏幕左侧(仅沿水平轴)。 但是,它可以保持瞬间传送。
代码的作用 =无止境地从一个精灵变成另一个精灵。 当更改为另一个精灵时,它也会更改其比例。
我想要的代码 =在更改为其他精灵之前,在水平轴上向左移动。
我尝试了线性插值(lerp)和transform.translate。
public class Transitions : MonoBehaviour
{
public Sprite Pokemon_0; // VARIABLES FOR SPRITES (Pokemons/ game objects)
public Sprite Pokemon_1;
float timer = 1f; // CHANGING SPRITES VALUES (delays)
float delay = 5f;
Vector2 temp; //CHANGING POSITION VARIABLES
Vector2 tempPos;
Vector2 finalPosition;
void Start()
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_0;
}
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
if (this.gameObject.GetComponent<SpriteRenderer>().sprite == Pokemon_0) // TO CHANGE FROM POKEMON 1 TO POKEMON 2
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_1;
temp = transform.localScale; // TO SET THE SCALE WHEN EACH POKEMON CHANGES (works)
temp.x = -380;
temp.y = 350;
transform.localScale = temp;
timer = delay;
finalPosition = new Vector2(167, -107);
transform.position = Vector3.Lerp(transform.position, finalPosition, 1f * Time.deltaTime);
//tempPos = transform.position; // Tried and tested method. Doesn't work.
//tempPos.x = 1f;
//transform.position = tempPos;
return;
}
if (this.gameObject.GetComponent<SpriteRenderer>().sprite == Pokemon_1) // TO CHANGE BACK FROM POKEMON 2 TO POKEMON 1
{
this.gameObject.GetComponent<SpriteRenderer>().sprite = Pokemon_0;
timer = delay;
return;
}
}
在执行时,此代码会更改口袋妖怪并更改比例。 但是,位置保持不变。
我很新,所以我一直在尝试我们的不同建议,谢谢。
在您的代码示例中,似乎您在不同地使用位置的x值。 xy和z值一起使用以形成一个点,该点在3D环境中表示。 每次将x值更改为1时,将对象的位置设置为先前的位置将其锁定在水平轴上。
您可以使用插值法来平滑两个位置状态之间的过渡,也可以使用Unity内置的Vector3.MoveTowards(如果在2D景观中则为Vector2)。
插补
您想要的位置就是您要更改的确切位置。 您当前的位置将是transform.position
。
float step; // Set this to how fast you want to increment movement (1f, 5f, 10f)
Vector3 start; // Set this to the transform.position when you want to start interpolating
Vector3 desired; // Set this to a new Vector3(x, y) with the place you want to move to
void Update(){
// Here, we set the object's position to it's current position, but interpolated to it's desired position
transform.position = Vector3.Lerp(start, desired, step * Time.deltaTime);
}
朝着去
float step; // Set this to how fast you want to increment movement (1f, 5f, 10f)
Vector3 desired; // Set this to a new Vector3(x, y) with the place you want to move to
void Update(){
transform.position = Vector3.MoveTowards(transform.position, desired, step * Time.deltaTime);
}
最好使用补间引擎,例如http://dotween.demigiant.com/ 。
如果您安装Dotween,则只需使用
transform.DOMove(new vector3(1 ,0 , 1) , duration);
您也可以为补间设置缓动。 或使用不完整功能;
transform.DOMove(new vector3(1 ,0 , 1) , duration)
.SetEase(Ease.OutCubic)
.OnCompelete(() => { shouldClose = true; });
您还可以为补间.SetLoops(-1)
设置循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.