- Home /
2D character script causing player to go off screen?
I am very new to C#, so the errors might be obvious. I'm trying to make a 2D character controller and the script I have runs, but when I hit play the player goes off the screen to the right and I am unable to control it, if that makes sense? Does anyone see the error in the script?
using UnityEngine;
using System.Collections;
public class RobotControllerScript : MonoBehaviour
{
public float maxSpeed = 10f;
bool facingRight = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700f;
bool doubleJump = false;
void Start ()
{
anim = GetComponent<Animator> ();
}
void FixedUpdate ()
{
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", grounded);
if (grounded)
doubleJump = false;
anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);
if(!grounded) return;
float move = Input.GetAxis ("Horizontal");
anim.SetFloat ("Speed", Mathf.Abs (move));
rigidbody2D.velocity = new Vector2(move + maxSpeed, rigidbody2D.velocity.y);
if (move > 0 && !facingRight)
Flip ();
else if (move < 0 && facingRight)
Flip ();
}
void Update ()
{
if ((grounded || !doubleJump) && Input.GetKeyDown (KeyCode.Space))
{
anim.SetBool("Ground", false);
rigidbody2D.AddForce(new Vector2(0, jumpForce));
if(!doubleJump && !grounded)
doubleJump = true;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Answer by b1gry4n · Nov 11, 2014 at 06:06 PM
rigidbody2D.velocity = new Vector2(move + maxSpeed, rigidbody2D.velocity.y);
your character will move in the X direction by 10 units every update since your maxspeed is being added to move.
Even with no input, the script reads...
rigidbody2D.velocity = new Vector2(0 + 10.0f, rigidbody2D.velocity.y);
you want to multiply it
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
If input is 0 your X velocity will be 0. If input is 1 your X velocity will be 10. if input is -1 your X velocity will be -10.
Your answer
![](https://koobas.hobune.stream/wayback/20220613171236im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do add gravity? 2 Answers
CharacterMotor CS Problem when export 0 Answers
Switching character controllers on key command? 3 Answers
character controller 1 Answer
Collision without rigidbody or character controller 1 Answer