0
votes

The problem is simple: I have a player with a rigidbody 2d and a collider 2d attached to it and I have a wall with a collider 2d attached to it. When I move the player against the wall they do collide but my player starts to shake really fast and it looks like it wants to pass through the wall.

GIF: http://gph.is/2ENK3ql

I need the player to stop moving when it collides with a wall and to deny any further movement towards the wall without disrupting movement away from the wall.

Player movement code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {
// Variables
public bool moving = true;
float playerMovSpeed = 5.0f;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (moving == true)
    {
        PlayerMove();
    }
    PlayerMoveCheck();
}

public void Set_moving(bool val)
{
    moving = val;
}

void PlayerMove()
{
    if (Input.GetKey(KeyCode.W))
    {
        transform.Translate(Vector3.up * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.A))
    {
        transform.Translate(Vector3.left * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.S))
    {
        transform.Translate(Vector3.down * playerMovSpeed * Time.deltaTime, Space.World);
    }

    if (Input.GetKey(KeyCode.D))
    {
        transform.Translate(Vector3.right * playerMovSpeed * Time.deltaTime, Space.World);
    }
}

void PlayerMoveCheck()
{
    if (Input.GetKey(KeyCode.W) != true && Input.GetKey(KeyCode.A) != true && Input.GetKey(KeyCode.S) != true && Input.GetKey(KeyCode.D) != true)
    {
        moving = false;
    }
    else
    {
        moving = true;
    }
}

Thanks in advance.

1
Please post your code relevant to the player moving and colliding with the wall.ryeMoss
I added the code to the question. The wall doesn't contain any code, just a collider 2d.user7007746

1 Answers

0
votes

transform.Translate() essentially acts as a teleportation of your transform. This means that your player is being put into its new coordinates, and then sees there is a collision and pushes it out - which is why your character "vibrates" against the wall. Instead, you should consider adding a rigidbody to your player and modifying the movement using .velocity or .position or ".AddForce()" which will take the physics of the collision into the account during movement.

You can do something like the following for force movement:

void Update()
{
    rbody.velocity = rbody.velocity * .9f; // custom friction

    if (Input.GetKey(KeyCode.W))
        rbody.AddForce(Vector2.up * speed);
    if (Input.GetKey(KeyCode.S))
        rbody.AddForce(Vector2.down * speed);
    // repeat for A and D
}