- Home /
Question by
CassioTDS · Jan 24, 2020 at 08:31 AM ·
2d-platformervelocity2d-physics2d character
[2D] Character keeps sliding when I add velocity to the rigidbody2D?
Hello! I am new to Unity and would like to know if I could make my 2D character stop sliding when I release the W key or the S key (W=Forward, S=Backwards). I tried messing with Rigidbody2D but it keeps sliding. Any help? Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
public Rigidbody2D rb;
public bool isGrounded = false;
void Update()
{
if(Input.GetKey("w")){
rb.velocity += new Vector2(1,0);
transform.rotation = Quaternion.Euler(0, 0, 0);
}
if(Input.GetKey("s")){
rb.velocity += new Vector2(-1,0);
transform.rotation = Quaternion.Euler(0, 180, 0);
}
if(Input.GetKeyDown("space")){
if(isGrounded == true){
rb.velocity += new Vector2(0,10);
}
}
}
void OnCollisionEnter2D (Collision2D col){
if(col.collider.tag=="Ground"){
isGrounded=true;
}
}
void OnCollisionExit2D (Collision2D col){
if(col.collider.tag=="Ground"){
isGrounded=false;
}
}
}
Comment
Best Answer
Answer by HAndLol · Jan 24, 2020 at 03:52 PM
try this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
public Rigidbody2D rb;
public bool isGrounded = false;
void FixedUpdate() //FixedUpdate is better than Update when working with a rigidbody
{
if(Input.GetKey("w")){
rb.velocity += new Vector2(1,0);
transform.rotation = Quaternion.Euler(0, 0, 0);
}
if(Input.GetKey("s")){
rb.velocity += new Vector2(-1,0);
transform.rotation = Quaternion.Euler(0, 180, 0);
}
//if not getting the S or W keys pressed stop the player from moving on the x axis
if(!Input.GetKey("s") && !Input.GetKey("w")){
rb.velocity = new Vector2(0, rb.velocity.y);
}
if(Input.GetKeyDown("space")){
if(isGrounded == true){
rb.velocity += new Vector2(0,10);
}
}
}
void OnCollisionEnter2D (Collision2D col){
if(col.collider.tag=="Ground"){
isGrounded=true;
}
}
void OnCollisionExit2D (Collision2D col){
if(col.collider.tag=="Ground"){
isGrounded=false;
}
}
}
Your answer
Follow this Question
Related Questions
HOLD THE JUMP BUTTON TO JUMP HIGHER 0 Answers
Mario Styled Jumping 1 Answer
Velocity in Unity2D 2 Answers
HOLD JUMP BUTTON TO JUMP HIGHER 2 Answers