Hey guys, so I’m trying to make a platform game as a beginner, and one of the main mechanics is a grappling hook. Prior to the grappling hook, the player can jump around on all platforms and not fall through it. However, when I use the grappling hook, my player while grappling can just fall through the platforms.
How do I fix this?
Here’s what it looks like for reference (the line is the player grappling on it and has fallen through the platform):
And this is my code for my player(movement and grappling hook):
public class Sal : MonoBehaviour
{
public Rigidbody2D sal;
public float movespeed = 2f;
public float jumpspeed = 2f;
public Transform groundCheck;
public LayerMask groundLayer;
public float groundCheckRadius;
public bool isTouchingGround = true;
private LineRenderer lineRend;
private DistanceJoint2D hook;
public
// Start is called before the first frame update
void Start()
{
sal = GetComponent<Rigidbody2D>();
lineRend = GetComponent<LineRenderer>();
hook = gameObject.AddComponent<DistanceJoint2D>();
lineRend.enabled = false;
lineRend.useWorldSpace = true;
hook.enabled = false;
}
// Update is called once per frame
void Update()
{
Movement();
lineRend.SetPosition(0,transform.position);
if (Input.GetKeyDown("space")){
shoot();
}
if (Input.GetKeyUp("space")){
hook.connectedBody = null;
lineRend.enabled = false;
hook.enabled = false;
}
}
void OnCollisionEnter2D(Collision2D ground){
if (ground.gameObject.tag == "ground"){
isTouchingGround = true;
}
}
void OnCollisionExit2D(Collision2D ground)
{
if(ground.gameObject.tag == "ground"){
isTouchingGround = false;
}
}
private void Movement(){
if(Input.GetKeyDown(KeyCode.UpArrow) == true && isTouchingGround){
sal.velocity = new Vector2(sal.velocity.x, jumpspeed);
}
if(Input.GetKey(KeyCode.LeftArrow) == true){
transform.Translate(Vector2.left * movespeed * Time.deltaTime);
}
if(Input.GetKey(KeyCode.RightArrow) == true){
transform.Translate(Vector2.right * movespeed * Time.deltaTime);
}
}
public void shoot(){
Vector3 shotDirection = ShootingDirection();
int layerMask = LayerMask.GetMask("Ground");
RaycastHit2D hit = Physics2D.Raycast(transform.position, shotDirection, 10f, layerMask);
if (hit.collider != null){
hook.enabled = true;
hook.connectedAnchor = hit.point;
lineRend.enabled = true;
lineRend.SetPosition(1, hit.point);
}
else{
lineRend.enabled = false;
hook.enabled = false;
}
}
private Vector3 ShootingDirection(){
Vector2 velocity = sal.velocity;
Vector3 forwardDirection;
if (Input.GetKey(KeyCode.RightArrow)){
forwardDirection = new Vector3(velocity.x + 5f, velocity.y, 0f).normalized;
}
else if (Input.GetKey(KeyCode.LeftArrow)){
forwardDirection = new Vector3(velocity.x - 5f, velocity.y, 0f).normalized;
}
else{
forwardDirection = new Vector3(velocity.x, velocity.y, 0f).normalized;
}
Vector3 upwardDirection = Vector3.up;
Vector3 shotDirection = forwardDirection + upwardDirection;
return shotDirection.normalized;
}
}