Object refuses to collide
Im trying to implement bunnyhopping as a mechanic in my game, but collisions dont work if I use MoveGround as the movement function, but collision work if I use the CharacterController Move function. The capsule the script is attached to just falls through a cube I have as a floor.
If anyone could help solve this that would be fantastic
public class PlayerScript : MonoBehaviour
{
public float moveSpeed = 0;
public float jumpHeight = 0;
public float gravity = 0;
public float friction = 0;
public float groundAccelerate = 0;
public float airAccelerate = 0;
public float maxVelocityGround = 0;
public float maxVelocityAir = 0;
CharacterController player;
Vector3 currPos;
Vector3 nextPos;
float distance;
int platLayer;
void Start ()
{
player = GetComponent<CharacterController>();
currPos = transform.position;
distance = player.radius + 0.2f;
}
void Update ()
{
if(player.isGrounded)
{
nextPos = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
nextPos = transform.TransformDirection(nextPos);
nextPos *= moveSpeed;
if(Input.GetKey(KeyCode.Space))
{
nextPos.y = jumpHeight;
}
}
transform.position -= Vector3.up * gravity * Time.deltaTime;
transform.position += MoveGround(nextPos, currPos) * Time.deltaTime;
/* Collision Checking */
RaycastHit hit;
Vector3 p1 = transform.position + Vector3.up * 0.25f;
Vector3 p2 = p1 + Vector3.up * player.height;
for(int i=0; i<360; i+=36)
{
if(Physics.CapsuleCast(p1,p2,0,new Vector3(Mathf.Cos(i), 0, Mathf.Sin(i)), out hit, distance, 1 << platLayer))
{
player.Move(hit.normal*(distance-hit.distance));
}
}
}
private Vector3 Accel(Vector3 accelDir, Vector3 prevVelocity, float accelerate, float mVel)
{
float projVel = Vector3.Dot(prevVelocity, accelDir);
float accelVel = accelerate * Time.fixedDeltaTime;
if(projVel + accelVel > mVel){ accelVel = mVel - projVel; }
return prevVelocity + accelDir * accelVel;
}
private Vector3 MoveGround(Vector3 accelDir, Vector3 prevVelocity)
{
float speed = prevVelocity.magnitude;
if (speed != 0)
{
float drop = speed * friction * Time.fixedDeltaTime;
prevVelocity *= Mathf.Max(speed - drop, 0) / speed;
}
return Accel(accelDir, prevVelocity, groundAccelerate, maxVelocityGround);
}
private Vector3 MoveAir(Vector3 accelDir, Vector3 prevVelocity)
{
return Accel(accelDir, prevVelocity, airAccelerate, maxVelocityAir);
}
}
Comment
Your answer
Follow this Question
Related Questions
How To how ?? 2 Answers
Ignore collision based on position 1 Answer
Adding Gravity to a game object to make a black hole sucking effect. 1 Answer
ontriggerexit not working 0 Answers
Checking for collisions 1 Answer