![](/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.