Answer by Ninjapro2k_ · Nov 25, 2016 at 08:34 PM
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
//You'll need all these bools and floats
[HideInInspector]
public bool facingRight = true;
[HideInInspector]
public float moveForce = 365;
public float maxSpeed = 5f;
public float jumpForce = 1000f;
public Transform groundCheck;
float groundRadius = .2f;
public LayerMask whatIsGround;
private bool grounded = false;
private Rigidbody2D rb2d;
// When the scene starts, grab the RB2d component
void Awake()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//Basically a small area that checks for ground under the player
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
//If I press jump and i'm touching the ground, jump is true
if (Input.GetButtonDown("Jump 1") && grounded)
{
jump = true;
}
}
//Standard movement stuff adapted from the official tutorial
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal 1");
if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);
if (Mathf.Abs(rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);
//If i'm moving right but not facing right, flip me
if (h > 0 && !facingRight)
Flip();
//If i'm moving left but facing right, flip me
else if (h < 0 && facingRight)
Flip();
//If jump is true, push me forward 0 degrees, and upward the value of jumpForce
if (jump)
{
rb2d.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}
//facing right = not facing right; theScale = my local scale in the inspector; the x value of theScale = the negative of it's current value; my local scale in the inspector now equals the negative of it's current value (e.g. 30 now equals -30)
void Flip()
{
facingRight = !facingRight;
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
For this you just need a player, with an empty gameObject called as a child. That child should be placed just at the player's feet. Of course attach Rigidbody2D to player. Hope this helps somebody :)
Oh, and for the layermask: basically this makes it so anything marked true will be seen as ground.
In the inspector, whatever you don't want to be labeled as ground (e.g. players, walls, projectiles), uncheck them in the layermask. Ground Check should not be marked as ground.
Answer by Midane53 · Nov 23, 2016 at 07:32 AM
I don't get how questions like this are approved by moderation and get shown up in the main questions " wall ". :V
Your answer
Follow this Question
Related Questions
Sprite 2D Flip issue 1 Answer
Unity2D animation and sprite layout 0 Answers
Applying one sprite/texture across multiple gameobjects. (2D) 0 Answers
Fliping a sprite 1 Answer
Inverse Sprite Maskin 0 Answers