Im making a Spiderman game and have added swinging to it. When the player swings however, they are able to go through walls and floor. Here is a video of it happening:
https://www.reddit.com/r/Unity3D/comments/waanl9/my_player_can_go_through_walls_when_swinging_info/
Here is the code used for the swining
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Pendulum
{
public Transform bob_tr;
public Tether tether;
public Arm arm;
public Bob bob;
public bool Swinging;
Vector3 previousPosition;
public GameObject Player;
public void Initialize()
{
bob_tr.transform.position = Player.transform.position;
bob_tr.transform.parent = tether.tether_tr;
Swinging = false;
}
public Vector3 MoveBob(Vector3 pos , float time)
{
if (Input.GetMouseButtonDown(0))
{
Swinging = true;
}
else if (Input.GetMouseButtonUp(0))
{
Swinging = false;
}
if(Swinging == false)
{
arm.length = Vector3.Distance(bob_tr.transform.localPosition, tether.position);
}
bob.velocity += GetConstrainedVelocity(pos , previousPosition , time);
bob.ApplyGravity();
bob.ApplyDamping();
bob.CapMaxSpeed();
pos += bob.velocity * time;
if(Vector3.Distance(pos , tether.position) < arm.length)
{
pos = Vector3.Normalize(pos - tether.position) * arm.length;
return pos;
}
previousPosition = pos;
return pos;
}
public Vector3 MoveBob(Vector3 pos , Vector3 prevPos , float time)
{
if (Input.GetMouseButtonDown(0))
{
Swinging = true;
}
else if (Input.GetMouseButtonUp(0))
{
Swinging = false;
}
if(Swinging == false)
{
arm.length = Vector3.Distance(bob_tr.transform.localPosition, tether.position);
}
bob.velocity += GetConstrainedVelocity(pos , prevPos , time);
bob.ApplyGravity();
bob.ApplyDamping();
bob.CapMaxSpeed();
pos += bob.velocity * time;
previousPosition = pos;
return pos;
}
public Vector3 GetConstrainedVelocity(Vector3 currentPos, Vector3 previousPosition , float time)
{
float distanceToTether;
Vector3 constrainedPosition;
Vector3 predictedPosition;
distanceToTether = Vector3.Distance(currentPos , tether.position);
if(distanceToTether > arm.length)
{
constrainedPosition = Vector3.Normalize(currentPos - tether.position) * arm.length;
predictedPosition = (constrainedPosition - previousPosition) / time;
return predictedPosition;
}
return Vector3.zero;
}
public Vector3 Fall(Vector3 pos , float time)
{
arm.length = Vector3.Distance(bob_tr.transform.localPosition, tether.position);
bob.ApplyGravity();
bob.ApplyDamping();
bob.CapMaxSpeed();
pos += bob.velocity * time;
return pos;
}
}
Thanks in advanced!