- Home /
Gravity switch
Hi everyone! Currently I am making a 2D runner where the player must avoid obstacles by switching its gravity. Before I was using scrolling method for my obstacles but later I realized that it is not what I want because sometimes obstacles are too fat and they appear in each other or too close to each other, so I decided to change it . Now the player has a force forward and I built the whole level and each obstacle by myself .But when I am changing the gravity it pushes my character forward and increases its speed. How to fix it ? I just want my player to stay on the same x axis during the jump. I tried to play with mass and speed and gravity scale but it doesn’t help …Check my script below :
private Rigidbody2D rb;
private bool top;
bool isGameOver = false;
public float speed = 2000f;
ChallengeScroller myChallengecontroller;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody2D>();
myChallengecontroller = GameObject.FindObjectOfType<ChallengeScroller>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !isGameOver)
{
rb.gravityScale *= -1;
}
}
private void FixedUpdate()
{
rb.AddForce(transform.right * speed);
}
void Rotation()
{
if (top == false)
{
transform.eulerAngles = new Vector3(0, 0, 180f);
}
else { transform.eulerAngles = Vector3.zero; }
top = !top;
}
void GameOver()
{
isGameOver = true;
myChallengecontroller.GameOver();
}
void OnCollisionEnter2D(Collision2D other)
{
if(other.collider.tag == "enemy")
{
GameOver();
}
}
}
Answer by Zaeran · Oct 12, 2018 at 03:49 PM
Your problem is most likely here
private void FixedUpdate()
{
rb.AddForce(transform.right * speed);
}
Since you're adding force every Fixedupdate, you're only going to keep increasing the speed of your character. When your character isn't touching the ground, there isn't any friction applied, so they will appear to speed up when in the frictionless air.