unity movement script 2d
//This is a script for a 2D plataformer type of movement.
//This script includes the movement, flipping the player and a ground check if you need one.
/*
This is a two in one grepper answer,
the script flips the player by rotating it,
and when it rotates, if the camera
is attached to the player the normal way,
its going to rotate the hole camera.
and the only way to fix that bug is by making it so
the camera follows you with code,
if you scroll all the way down you can find the code that makes
the camera follow the player.
*/
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float movementSpeed = 1;
private Rigidbody2D rb;
public float JumpForce = 1;
//If the character flipps the wrong way change this variable to false.
public bool facingRight = true;
public Camera cam;
public bool isGrounded = false;
public Transform GroundCheck;
public LayerMask Ground;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Xmovement();
GroundCheck();
Jump();
void Xmovement()
{
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * movementSpeed;
if (Input.GetAxis("Horizontal") > 0)
{
facingRight = false;
}
if (Input.GetAxis("Horizontal") < 0)
{
facingRight = true;
}
//Flipping the player
if (facingRight) {
transform.eulerAngles = new Vector3(0, 180, 0);
}
}
void Jump()
{
if (Input.GetButtonDown("Jump") && Mathf.Abs(rb.velocity.y) < 0.001f)
{
rb.AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse);
}
}
void GroundCheck()
{
if (Mathf.Abs(rb.velocity.y) < 0.001f)
{
isGrounded = true;
}
else
{
isGrounded = false;
}
}
}
}
/*
Read the commented lines on the top of the answer for context.
*/
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Camera cam;
public Transform subject;
// Update is called once per frame
void LateUpdate()
{
cam.transform.position = subject.transform.position ;
}
}