- Home /
2D Character grabing the wall
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);
}
}
If you look in the 2D tutorial you can see the character get stuck also. This is probably a bug in unity and not something wrong with your code
Answer by ziv03 · Dec 07, 2013 at 07:35 PM
You need to add a physics2d material to the wall, setting the friction to 0. steps:
create a physics2d material from the assets and set its friction to 0
select your wall gameobject, and in the boxcollider2d component, set the material to the material you just created
Your answer
![](https://koobas.hobune.stream/wayback/20220613083138im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D Animation does not start 1 Answer
Movement restriction... 1 Answer
Don't move unless in BoxCollider2D (C#) 1 Answer