Circle kind of clipping in the wall
So, I'm making my first game (a platformer) and (at least for now) you are playing as a circle, but whenever I move into a wall (move forward into a wall continuously) the circle is somewhat glitching into a wall a little bit and it also causes for the character to fall a little slower. It glitches like one frame it is in the wall, another it is just normally touching the wall. I don't know what could cause such behavior. Anybody knows how to fix this?
I was making a 2d platformer myself a while ago, and I had similar problems until I did a bit of research and created a script that worked well.
public class mainScript : MonoBehaviour { private Rigidbody2D rb; private float moveInputH; public float speed = 15; public float jumpSpeed, xOffset, yOffset, xSize, ySize; public bool isGrounded; public LayerMask groundMask; float horizontalMove = 0f; public float runSpeed = 4f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
jumpSpeed = 15;
}
void Update()
{
moveInputH = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector3(moveInputH * speed, rb.velocity.y);
float horizontal = Input.GetAxis("Horizontal");
isGrounded = Physics2D.OverlapBox(new Vector2(transform.position.x + xOffset, transform.position.y + yOffset), new Vector2(xSize, ySize), 0f, groundMask);
if(Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
if(Input.GetKeyDown(KeyCode.W) && isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpSpeed);
}
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawCube(new Vector2(transform.position.x + xOffset, transform.position.y + yOffset), new Vector2(xSize, ySize));
}
}
There was originally some code for animation and flipping directions, but as a circle, your character probably won't need that. You might think that this wouldn't work because it has no way to detect keys other than arrows, but unity moves it when a key is pressed automatically. This is tried and true, and worked really well for me. Let me know if it works. Good luck!
Answer by Blueshrimps · Mar 16 at 02:12 PM
Are you using a rigidbody, or a character controller to move?
Your answer
Follow this Question
Related Questions
Trying to prevent click& drag camera from going through mesh, rigidbody makes it bounce like crazy 0 Answers
How to prevent a Rigidbody on collision to NOT do anything? 0 Answers
My player's rigidbody 2d is being continuously pushed downwards by box collider 2d 1 Answer
Rigidbody Position And Rotation Freeze makes player go through the object 0 Answers
Pushable Boxes in 3d ISO game 0 Answers