- Home /
Player glitching through wall when sprinting
Hello,
I have a 2d Game and a standard Player Controller for letting my player move. When I'm moving without pressing "Sprint" collisions work, but when the players is sprinting it just runs through walls...My Walls are tilemaps with tilemap colliders and composite colliders (Even tried to turn them off to normal box colliders, but no difference). Hope you can help me. Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementPlayer : MonoBehaviour
{
public CharacterController charController;
public Vector2 direction;
private Vector3 change;
public bool sprint;
[SerializeField]
public float walkingSpeed;
public float runningSpeed;
void Start()
{
runningSpeed = walkingSpeed *1.5f;
}
// Update is called once per frame
void Update()
{
//Animation
change = Vector3.zero;
change.x = Input.GetAxis("Horizontal");
change.y = Input.GetAxis("Vertical");
charController.animate(change);
//Movement
if(change != Vector3.zero) { getDirection(); }
}
// FixedUpdate is called once per "time"
void FixedUpdate()
{
moveChar();
}
void moveChar()
{
if (sprint)
{
transform.Translate(direction * runningSpeed * Time.fixedDeltaTime);
}
else
{
transform.Translate(direction * walkingSpeed * Time.fixedDeltaTime);
}
}
void getDirection()
{
direction = Vector2.zero;
if (Input.GetKey(KeyCode.W))
{
direction += Vector2.up;
}
if (Input.GetKey(KeyCode.A))
{
direction += Vector2.left;
}
if (Input.GetKey(KeyCode.S))
{
direction += Vector2.down;
}
if (Input.GetKey(KeyCode.D))
{
direction += Vector2.right;
}
if (Input.GetKey(KeyCode.LeftShift))
{
sprint = true;
}
if (!Input.GetKey(KeyCode.LeftShift))
{
sprint = false;
}
}
}
You have to move the object with its rigidbody component if you want better collision detection. So change your moveChar
and use $$anonymous$$ovePosition
function.
Answer by xill · Aug 23, 2019 at 10:38 AM
What Hellium says. Transform.translate forces the object to move next position so there is no physics involved. It's like picking the obj and putting it in its next frame position.