[英]Character rotates but only moves towards one direction. (Unity 2d)
I am unable to "move" the character towards the "left" direction.我无法将角色“移动”到“左”方向。 It moves only towards "right" direction when I press both, "a" AND "d".
当我同时按下“a”和“d”时,它只会向“右”方向移动。 However, I am able to rotate the character to either direction according to the key pressed.
但是,我可以根据按下的键将角色旋转到任一方向。
It is kind of moonwalking when I press the left key, I don't want my character to follow the footsteps of the late MJ.当我按下左键时有点像月球漫步,我不希望我的角色跟随已故 MJ 的脚步。
private void FixedUpdate()
{
//On X axis: -1f is left, 1f is right
//Player Movement. Check for horizontal movement
if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
{
if (Input.GetKey("left shift"))
{
moveSpeed = runSpeed;
}
else {
moveSpeed = 5f;
}
transform.Translate(new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f));
if (rb2d.velocity.y == 0 && !isslashing)
animator.Play("player_run");
if (Input.GetAxisRaw("Horizontal") > 0.5f && !facingRight)
{
//If we're moving right but not facing right, flip the sprite and set facingRight to true.
Flip();
facingRight = true;
}
else if (Input.GetAxisRaw("Horizontal") < 0.5f && facingRight)
{
//If we're moving left but not facing left, flip the sprite and set facingRight to false.
Flip();
facingRight = false;
}
}
else
{
if (rb2d.velocity.y == 0 && !isslashing)
animator.Play("idleanim");
}
}
void Flip()
{
//Switch the way the player is labelled as facing
facingRight = !facingRight;
transform.Rotate(0f, 180f, 0f);
}
Transform.Translate
defaults to moving in local space and since you're rotating the transform, it's easiest if you just have it move in world space since you are already creating a world space vector. Transform.Translate
默认在局部空间中移动,并且由于您正在旋转变换,所以如果您只是让它在世界空间中移动是最简单的,因为您已经创建了一个世界空间向量。
You can do this by adding Space.World
as an argument to Transform.Translate
:您可以通过将
Space.World
作为参数添加到Transform.Translate
来实现:
Vector3 moveVector = Input.GetAxisRaw("Horizontal") * moveSpeed
* Time.deltaTime * Vector3.right;
transform.Translate(moveVector, Space.World);
By the way, you're already toggling the value of movingRight
inside of Flip
, so there is no reason to set it again after you call Flip
.顺便说一句,您已经在
Flip
内部切换movingRight
的值,因此没有理由在您调用Flip
后再次设置它。 Might as well just call it and be done with those blocks:不妨调用它并完成这些块:
if (Input.GetAxisRaw("Horizontal") > 0.5f && !facingRight)
{
// If we're moving right but not facing right, flip the sprite
// and set facingRight to true.
Flip();
}
else if (Input.GetAxisRaw("Horizontal") < 0.5f && facingRight)
{
// If we're moving left but not facing left, flip the sprite
// and set facingRight to false.
Flip();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.