I am making a 2d platformer game and I need help on coding this script that makes the player walk through walls when a key is pressed and not lose gravity + do not fall through the platform.
// Start is called before the first frame update
void Start()
{
rigidBody = GetComponent();
bodyCollider = GetComponent();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetButton("Phase"))
{
rigidBody.gravityScale = 1;
bodyCollider.isTrigger = true;
}
else
{
rigidBody.gravityScale = 1;
bodyCollider.isTrigger = false;
}
}
I’m going to write you a seperate script that will do exactly what you want, but this really should be attatched to something like a player controller script or the script that translates input.
In this example, you need to attach this directly to the player, set all the walls to a tag (for the example I provided, it will be “Walkthrough”) and the key you need to press will be “L” (only because I would assume it doesn’t conflict with any other button you might have mapped, you would need to set that to something else if you don’t want the player to press and hold “L” and on release it will make the walls solid again)
using UnityEngine;
using System.Collections.Generic;
public class WallScript : MonoBehaviour
{
List<GameObject> walls = new List<GameObject>();
private void Start()
{
walls = GameObject.FindGameObjectsWithTag("Walkthrough");
}
private void Update()
{
WalkthroughWalls();
}
private void WalkthroughWalls()
{
foreach(Collider2D col in walls)
{
if(Input.GetKeyUp(KeyCode.L)
{
col.enabled = true;
}
else if(Input.GetKey(KeyCode.L)
{
if(col.enabled = false)
{
return;
}
col.enabled = false;
}
}
}
}
I haven’t tested that with Unity, and am not such a wiz at coding that I might have not have the correct placement of the release the L key command to have the walls solid again, but I think that should work and if it doesn’t, please let me know what errors you get.