我正在Unity中进行一个小型实验项目。我有一个2d精灵,它以一定速度向前移动,但我希望它以宽弧度向左或向右旋转,并在按键时继续沿该方向移动。
代码段1:
bool forward = true;
Vector3 movement;
void FixedUpdate()
{
if (forward)
{
//Moves forward
movement = new Vector3(0.0f, 0.1f, 0.0f);
rb.velocity = movement * speed;
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
forward = false;
movement = new Vector3(-0.05f, 0.05f, 0.0f);
rb.velocity = movement * speed;
rb.angularVelocity = 30;
}
if (transform.rotation.z == 90)
{
movement = new Vector3(-0.1f, 0.0f, 0.0f);
rb.velocity = movement * speed;
rb.angularVelocity = 0;
}
}
代码段2:
void Update(){
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
Vector3 target = transform.position + new Vector3(-0.5f, 0.5f, 0);
transform.position
=Vector3.Lerp(transform.position,target,Time.deltaTime);
transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles,
new Vector3(0, 0, 90), Time.deltaTime);
}
}
任何人都可以为我指出实现此目标的正确方法的正确方向吗?
答案 0 :(得分:0)
不能完全确定这是否是您要完成的工作,但这是我想出的一些伪代码,可以帮助您入门...
基本上,当按下一个方向时,您想要增加该方向上的速度,直到所有速度都指向该方向为止。同时,您想将速度沿以前的方向减小,直到为零为止。
这是一个简化的公式-如果您确实希望速度在整个圆弧中保持恒定,则必须使用一些几何图形,知道V =(velX ^ 2 + velY ^ 2)^。5,但是这将使您非常接近...
float yvel = 1f, xvel;
float t;
void Update()
{
GetComponent<Rigidbody2D>().velocity = new Vector2(xvel, yvel);
t += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.D))
{
t = 0;
StartCoroutine(Move());
}
}
private IEnumerator Move()
{
while (t < 2) // at time t, yvel will be zero and xvel will be 1
{
yvel = 1 - .5f * t; // decrease velocity in old direction
xvel = .5f * t; // increase velocity in new direction
yield return null;
}
}