So basically I want to change players scale.x to negative if player is moving to left. I've managed to write a script but it just won't change it's scale. I tried every thing but it won't work. Logically it should work but it doesn't and i can't identify the error. Here's my script:
public float speedX;
bool facingRight;
float speed;
void Start() {
facingRight = true;
}
void Update()
{
MovePlayer(speed);
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
speed = -speedX;
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
speed = 0;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
speed = speedX;
}
if (Input.GetKeyUp(KeyCode.RightArrow))
{
speed = 0;
}
if (Input.GetKeyDown(KeyCode.UpArrow)) {
Jumping = true;
rb.AddForce(new Vector2(rb.velocity.x, jumpSpeedY));
}
}
void MovePlayer(float playerSpeed) {
rb.velocity = new Vector3(speed, rb.velocity.y, 0);
}
void Flip() {
if (speed > 0 && !facingRight || speed < 0 && facingRight) {
facingRight = !facingRight;
Vector3 temp = transform.localScale;
temp.x *= -1;
transform.localScale = temp;
}
}
CodePudding user response:
Logically it should work
Nothing is ever calling Flip
.
You probably wanted to add it to
private void Update()
{
...
Flip();
}
As mentioned though the input handling looks pretty odd to me. You should probably rather simply use
speed = Input.GetRawAxis("Horizontal") * speedX;
and then rather call MovePlayer
within FixedUpdate
so
private void Update()
{
speed = Input.GetRawAxis("Horizontal") * speedX;
Flip();
}
private void FixedUpdate()
{
// questionable if you need a dedicated method for a one-liner ;)
MovePlayer(speed);
}
Also as already said though you are dealing with the physics engine here and most probably should not simply change the scale via the Transform
component.
I assume a 2D game so rather use e.g. SpriteRenderer.flipX
.
CodePudding user response:
Try this ? add ( )
in conditions
void Flip()
{
if ((speed > 0 && !facingRight) || (speed < 0 && facingRight)) {
facingRight = !facingRight;
Vector3 temp = transform.localScale;
temp.x *= -1;
transform.localScale = temp;
}
}