- Home /
Question by
AlexReverse · Jul 11, 2018 at 01:23 PM ·
c#scripting problemplayerscale
Player changes scale when i play the game
I was trying to make some movement animations and scripts but then when i played the game the player was really huge .Where is the mistake in my scripts?
PLAYER SCRIPT:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float maxspeed = 3;
public float speed = 50f;
public float jumppower = 150f;
public bool grounded;
private Rigidbody2D rb2d;
private Animator anim;
void Start () {
//player movement
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(1, 1, 1);
}
}
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
//limiting the speed
if (rb2d.velocity.x > maxspeed)
rb2d.velocity = new Vector2(maxspeed, rb2d.velocity.y);
rb2d.AddForce((Vector2.right * speed) * h);
if (rb2d.velocity.x < -maxspeed)
{
rb2d.velocity = new Vector2(-maxspeed, rb2d.velocity.y);
}
}
}
GROUND CHECK SCRIPT:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundCheck : MonoBehaviour{
private Player player;
void Start()
{
player = gameObject.GetComponentInParent<Player>();
}
void OnTriggerEnter2D(Collider2D col)
{
player.grounded = true;
}
void OnTriggerExit2D(Collider2D col)
{
player.grounded = false;
}
}
And this is how the player looks:
bandicam-2018-07-11-13-18-35-282.png
(15.8 kB)
Comment
Best Answer
Answer by JavierRuidoRosa · Jul 11, 2018 at 01:39 PM
I think the problem resides in this part of the Player script:
if (Input.GetAxis("Horizontal") < -0.1f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if (Input.GetAxis("Horizontal") > 0.1f)
{
transform.localScale = new Vector3(1, 1, 1);
}
Probably your transform scale in the scene is way smaller than (1,1,1), and reescalating it like this could make this giant appear. I suggest you to use an attribute of SpriteRenderer: flipX
public void SpriteRenderer spriteRenderer; //Assign this in inspector
void Update()
{
anim.SetBool("Grounded", grounded);
anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
if (Input.GetAxis("Horizontal") < -0.1f)
{
spriteRenderer.flipX = true;
}
if (Input.GetAxis("Horizontal") < 0.1f)
{
spriteRenderer.flipX = false;
}
}
I hope this helps!
I created a float float size = 0.2f;
then I wrote transform.localScale = new Vector3(-size , size , size);
and it worked, but I'll try your method too ^-^