Question by
PastaMilk · Jan 31 at 10:28 AM ·
unity 2dbooleanontriggerenter2d
OntriggerEnter2d not changing Boolean C#
Hello!
I'm having an issue where my moveRight bool is not changing when I'm colliding with an object tagged as a "Wall" but only when moveRight is marked as true too. If the Player (White square) collides with a Wall when moveLeft is True then the Player changes direction as expected. Gif and code is below. Any insight would be much appreciated!
Goal is to have the player constantly move in one direction based on the last key press OR if the player collides with a wall and forces a change in direction.
public class Character2DController : MonoBehaviour
{
public float movementSpeed;
public float jumpForce;
private Rigidbody2D _rb;
public bool moveRight, moveLeft;
void Start()
{
_rb = GetComponent<Rigidbody2D>(); //declare RB for jumping
moveRight = false;
moveLeft = false;
}
void Update()
{
if(Input.GetKeyDown(KeyCode.D))
{
moveRight = true;
moveLeft = false;
}
if (moveRight)
{
transform.position += new Vector3(1, 0, 0) * Time.deltaTime * movementSpeed;
}
if (Input.GetKeyDown(KeyCode.A))
{
moveLeft = true;
moveRight = false;
}
if (moveLeft)
{
transform.position += new Vector3(1, 0, 0) * Time.deltaTime * -movementSpeed;
}
//jumping
//by checking the y impulse velocity this limits jumping to only a single instance
if (Input.GetButtonDown("Jump") && Mathf.Abs(_rb.velocity.y) < 0.001f)
{
_rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Wall" && moveRight)
{
moveRight = false;
moveLeft = true;
}
if (other.tag == "Wall" && moveLeft)
{
moveRight = true;
moveLeft = false;
}
}
}
![alt text][2]
collider-issues2.gif
(435.1 kB)
collider-issues2.gif
(435.1 kB)
Comment