- Home /
2D movement colliding problem
With the new 2d features i have made a character that can move left and right. i use this script that i made:
var mSpeed : float = 0.1;
function Start () {
}
function Update () {
if(Input.GetButton("right"))
{
transform.Translate(Vector3(mSpeed,0,0) * Time.deltaTime);
}
if(Input.GetButton("left"))
{
transform.Translate(Vector3(-mSpeed,0,0) * Time.deltaTime);
}
}
Nothing special, you can't jump but i make that when i find out how to. But thats not the question.
My character also has a 2Drigidbody, and when i walk into an object and hold the button the player "lags". I can't really find a word for it. But the player goes like a little bit into the object and then out of it to noraml again. And this happens about 5 times every second. until i release the key. I hope you understand what i mean.
Answer by Squabbler · Jan 14, 2014 at 10:06 PM
I had a similar problem in my 2D overhead game with my enemies running into barriers and basically looking like they were having a seizure. The way got rid of this is have a trigger when touching another collider that prevents movement in that direction.
So for example, my enemies would run from top of the screen to the bottom. If they collided with a (left or right) "wall", then I wanted them to run diagonally the other direction (think the way a ball bounces off a wall at an angle). However if they collided with a barrier, I wanted them to stop completely and attack it.
In my enemy controller, I set up a trigger method to handle this:
// Triggers for colliders
private void OnTriggerEnter (Collider col) {
// Invisible walls are the left and right stage walls or boundaries
if (col.tag == "InvisibleWall") {
// If the enemy hit the left wall, run right
if (col.name == "LeftWall") {
RunRight();
// If the enemy hit the right wall, run left
} else if (col.name == "RightWall") {
RunLeft();
}
// If enemy hit a barrier, stop running
} else if (col.tag == "Barrier") {
StopRun();
InitiateAttackBarrier();
}
}
When I originally didn't have the StopRun() method, the enemy would just keep running and look like they are "bouncing" off the wall really fast. I had to set up a method to set their actual speed to ZERO until they weren't colliding with the barrier anymore. (which was only possible once they destroyed it, because the barrier collider would disappear)
Using the same logical principle I did, if you know the player's collider is touching an object's collider, just disable speed completely in that direction until those colliders aren't touching anymore. If the game is a side-scroller, then you might have to create multiple colliders for your character (left-side, right-side, head, etc), this way you know which direction's speed to disable.
Hope this helps a bit and gives you an idea.