Hello guys, I’m with problems on my character move.
When I jump to one wall my character grab the wall like spider man if I keep the direction buttom pressed, look like the gravity is disabled.
Thats my code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class movePlayer : MonoBehaviour
{
public float speed = 10.0f;
public float gravity = 10.0f;
public float maxVelocityChange = 10.0f;
public float jumpHeight = 2.0f;
private bool grounded = false;
public float airMove = 5.0f;
public float distGround = 1;
public bool checkGround;
void Awake()
{
rigidbody.freezeRotation = true;
rigidbody.useGravity = false;
}
void Update()
{
//Debug.Log("Ground:" + grounded);
//Debug.Log("Can Jump:" + canJump);
//Debug.Log(rigidbody.velocity.x);
checkGround = Physics.Raycast(transform.position, -Vector3.up, distGround);
Debug.LogWarning(checkGround);
// Calculate how fast we should be moving
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
targetVelocity = transform.TransformDirection(targetVelocity);
targetVelocity *= speed;
// Apply a force that attempts to reach our target velocity
Vector3 velocity = rigidbody.velocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
// Jump
if (checkGround)
{
speed = 10;
}
if (checkGround && Input.GetButton("Jump"))
{
rigidbody.velocity = new Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
}
if (!checkGround && rigidbody.velocity.x > 0)
{
if (Input.GetKey(KeyCode.A))
{
speed = 5;
}
}
else if (!checkGround && rigidbody.velocity.x < -0)
{
if (Input.GetKey(KeyCode.D))
{
speed = 5;
}
}
// We apply gravity manually for more tuning control
if (!checkGround)
{
rigidbody.AddForce(new Vector3(0, -gravity * rigidbody.mass, 0));
}
}
float CalculateJumpVerticalSpeed()
{
// From the jump height and gravity we deduce the upwards speed
// for the character to reach at the apex.
return Mathf.Sqrt(2 * jumpHeight * gravity);
}
}