- Home /
This question was
closed Jan 30, 2016 at 07:40 PM by
GeoDragn for the following reason:
The question is answered, right answer was accepted
Question by
GeoDragn · Jan 27, 2016 at 05:59 PM ·
2d-platformer
Platformer Character
So I've been working on a little platformer, and I've been trying to set up custom physics for the player. It works fine, until I add the ability to run. He seems to be going faster than my physics can keep up with. He keeps going into walls and slopes. Any idea how I should fix it? Thanks!
public float Y_Velocity;
public float X_Velocity;
private string dir;
private bool jumpKey;
public bool onGround;
public LayerMask mask;
void Start ()
{
}
void FixedUpdate ()
{
transform.rotation = Quaternion.Euler(0, 0, 0);
if (Input.GetKey("z") && Y_Velocity > 5.5f)
{
Y_Velocity = Y_Velocity - 0.5f;
}
else
{
Y_Velocity = Y_Velocity - 1;
}
transform.Translate(Vector3.up * Time.deltaTime * Y_Velocity);
if (!Physics2D.Raycast(transform.position + new Vector3(-0.2f, -1f, 0), Vector3.right, 0.4f, mask))
{
onGround = false;
}
if (Y_Velocity > 0)
{
while (Physics2D.Raycast(transform.position + new Vector3(-0.2f, 0.55f, 0), Vector3.right, 0.4f, mask))
{
Y_Velocity = 0;
transform.Translate(Vector3.down * Time.deltaTime);
}
}
if (Y_Velocity < 0)
{
while (Physics2D.Raycast(transform.position + new Vector3(-0.2f, -0.55f, 0), Vector3.right, 0.4f, mask))
{
Y_Velocity = 0;
transform.Translate(Vector3.up * Time.deltaTime);
onGround = true;
}
}
if (Input.GetKey("z") && jumpKey == false && Physics2D.Raycast(transform.position + new Vector3(-0.2f, -0.65f, 0), Vector3.right, 0.4f, mask))
{
Y_Velocity = 15;
jumpKey = true;
}
X_Velocity = X_Velocity * 0.7f;
transform.Translate(Vector3.right * Time.deltaTime * X_Velocity * 3);
if (Input.GetKey("right"))
{
if (Input.GetKey("a"))
{
X_Velocity = X_Velocity + 1;
}
X_Velocity = X_Velocity + 1;
dir = "right";
}
else if (Input.GetKey("left"))
{
if (Input.GetKey("a"))
{
X_Velocity = X_Velocity - 1;
}
X_Velocity = X_Velocity - 1;
dir = "left";
}
if (X_Velocity > 0)
{
while (Physics2D.Raycast(transform.position + new Vector3(0.25f, 0.55f, 0), Vector3.down, 0.9f, mask))
{
X_Velocity = 0;
transform.Translate(new Vector3(-0.1f, 0, 0) * Time.deltaTime);
}
}
if (X_Velocity < 0)
{
while (Physics2D.Raycast(transform.position + new Vector3(-0.25f, 0.55f, 0), Vector3.down, 0.9f, mask))
{
X_Velocity = 0;
transform.Translate(new Vector3(0.1f, 0, 0) * Time.deltaTime);
}
}
if (dir == "left")
{
transform.rotation = Quaternion.Euler(0, 180, 0);
}
if(!Input.GetKey("z"))
{
jumpKey = false;
}
}
Comment
Best Answer
Answer by FortisVenaliter · Jan 27, 2016 at 06:28 PM
For those collision checks, you need to factor in the speed instead of using hard-coded values. When the character is moving faster, your collision checks need to go further. Also, instead of stopping dead when you detect a collision, maybe move the character to the point of collision before stopping them.