Why does my charakter in unity gets stuck in the tilemap? - unity3d

In my Unity my Player gets everytime stuck in the collider when he has a big force (If he falls from a high place, The Gravity Scale or his jumppower is high). In the picture you can see Colliders and Renderer.
Only one Component is not on in screen at the platformcomponents, Tilemap.
Here is my code for Playermovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private LayerMask platformsLayerMask;
private Rigidbody2D rigidbody2d;
private BoxCollider2D boxCollider2d;
private void Awake()
{
rigidbody2d = transform.GetComponent<Rigidbody2D>();
boxCollider2d = transform.GetComponent<BoxCollider2D>();
}
private void Update()
{
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
float jump_power = 17.5f;
rigidbody2d.velocity = Vector2.up * jump_power;
}
HandleMovement();
}
private bool IsGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .1f, platformsLayerMask);
return raycastHit2d.collider != null;
}
private void HandleMovement()
{
float moveSpeed = 10f;
if (Input.GetKey(KeyCode.A))
{
rigidbody2d.velocity = new Vector2(-moveSpeed, rigidbody2d.velocity.y);
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody2d.velocity = new Vector2(+moveSpeed, rigidbody2d.velocity.y);
}
else
{
rigidbody2d.velocity = new Vector2(0, rigidbody2d.velocity.y);
}
}
}

Have you tried setting the player's rigidbody collision detection to continuous? If the collision detection is set to discrete, it's really easy to come accross this kind of problem when using the built in physics system

Related

How can I fix the following error, 'RenderBuffer' does not contain a definition for 'velocity', in unity c#?

I have a simple player movement script, but I am running into the following error 'RenderBuffer' does not contain a definition for 'velocity', and I don't know how to fix it.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting.Antlr3.Runtime.Tree;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D coll;
private bool hasDoubleJumped = false;
[SerializeField] private float moveSpeed = 7f;
[SerializeField] private float jumpForce = 14f;
[SerializeField] private LayerMask jumpableGround;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
coll = GetComponent<BoxCollider2D>();
}
private void Update()
{
float dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
hasDoubleJumped = false;
rb.velocity = new Vector2(RenderBuffer.velocity.x, jumpForce);
}
else if (Input.GetButtonDown("Jump") && !hasDoubleJumped)
{
hasDoubleJumped = true;
rb.velocity = new Vector2(RenderBuffer.velocity.x, jumpForce);
}
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpableGround);
}
}
I have tried changing a few things, but it doesn't seem to solve my problem.
On your jump logic you wrote RenderBuffer.velocity.x, seems out of place, try rb.velocity.x if you want to to access the current rigidbody velocity.
It looks like the problem is with the code RenderBuffer.velocity which is trying to access the velocity property of RenderBuffer, but velocity isn't a property of RenderBuffer. I notice you also have code like rb.veclocity where rb refers to a RigidBody (which does have a velocity property). Could you have a typo here? Perhaps you just need to replace RigidBody.velocity with rb.velocity in your code.

Unity Physics2D.OverlapBox is always returning true

I am trying to do ground detection for a 2d platformer, but my physics check is always returning true. I am reusing code that I have used a many times before:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("MOVEMENT")]
public float speed;
float inputX;
[Header("JUMPING")]
public float jumpForce;
public Transform feet;
public Vector2 checkSize;
public bool isGrounded;
public LayerMask layers;
public int extraJumps = 1;
int jumpTracker;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
inputX = Input.GetAxisRaw("Horizontal");
isGrounded = Physics2D.OverlapBox(feet.position, checkSize, 0f, layers);
if(Input.GetKeyDown(KeyCode.Space))
{
if (isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTracker = extraJumps;
}
else
{
if(jumpTracker > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTracker--;
}
}
}
}
private void FixedUpdate()
{
rb.velocity = new Vector2(inputX * speed, rb.velocity.y);
}
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(feet.position, checkSize);
}
}
In the scene there is a Tilemap with a composite collider tagged as ground that the player is colliding with.
I have tried everything I can think of and still have no idea what is causing this issue. Any help would be greatly appreciated.

Jump in using Rigidbody or Character controller

i have been recreating my jump code, i have it all done but i can't add force or anything else.
Here's my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class pBeh : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1;
public float Gravity = 9.8f;
private float velocity = 0;
private Camera mainCam;
public Rigidbody rb;
public float jumpSpeed = 5.2f;
private Vector3 movingDirection = Vector3.zero;
public CharacterController controller;
public float speed;
float turnSmoothVelocity;
public float turnSmoothTime;
public bool canJump = false;
private void Start()
{
characterController = GetComponent<CharacterController>();
mainCam = Camera.main;
}
void Update()
{
// player movement - forward, backward, left, right
float horizontal = Input.GetAxis("Horizontal") * 10;
float vertical = Input.GetAxis("Vertical") * 10;
Vector3 camRightFlat = new Vector3(mainCam.transform.right.x, 0,
mainCam.transform.right.z).normalized;
Vector3 camForwardFlat = new Vector3(mainCam.transform.forward.x, 0,
mainCam.transform.forward.z).normalized;
characterController.Move((camRightFlat * horizontal + camForwardFlat * vertical)
* Time.deltaTime);
// Gravity
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
if (canJump == true && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jumped");/*
transform.Translate(Vector3.up * 5.0f * Time.deltaTime);
rb.AddRelativeForce(Vector3.up * 8.0f);
rb.AddForce(Vector3.up * 8.0f)
i have tried a lot more, but it just doesn't work.
The sphere (Player) does nothing or shakes.
*/
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "enemy")
{
SceneManager.LoadScene("SampleScene");
}
}
void FixedUpdate()
{
if ((controller.collisionFlags & CollisionFlags.Below) != 0)
{
//Debug.Log("ground");
canJump = true;
}
else
{
canJump = false;
}
}
As i said it works just fine i just can't find reason why i cannot jump.
I have all character controller right and rigidbody too. If you could help i would be happy.
Btw i am beginner so i copied movement to be same as camera. Thanks!
From what I know, rigidbody and character controller do not work together (on the same object) so you have to choose one or the other, if you are using rigidbody then a ground check or similiar stuff would not be necessary since rigidbody is using unity physicis system so a lot of the stuff would be already done for you to simulate physics but you should still read thru the document

How to stop the player from jumping while in the air?

I don't want my player to jump in the air but I can't seem to find anything out.
This is what I have. They can jump, but they can jump forever and that's a problem.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed = 5f;
public float jumpSpeed = 8f;
private float movement = 0f;
public bool alive;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
// Use this for initialization
}
// Update is called once per frame
void Update () {
movement = Input.GetAxis ("Horizontal");
if (movement > 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else {
rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
}
if(Input.GetButtonDown ("Jump")){
rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
}
}
}
An simple option is to maintain a boolean such as _inAir that gets set to true when the player first jumps, and to false when their RigidBody2D collides with the ground (see, e.g., OnCollisionEnter2D).
Then, the check if(Input.GetButtonDown ("Jump")){ becomes
if (!_inAir && Input.GetButtonDown("Jump")) {

Trying to create a nice character controller?

I'm kind of new in the 2D environment of Unity.
I'm trying to create a platformer. For now, I have a simple map and my player.
My simple map and my player
My player have one script attached :
public class Player : MonoBehaviour
{
public float speed;
public float jump;
public GameObject raycastPoint; // Positioned at 0.01 pixel below the player
private SpriteRenderer spriteRenderer;
private Rigidbody2D body; // Gravity Scale of the Rigidbody2D = 50
private Animator animator;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
body = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
private void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
if (horizontal == 1 && spriteRenderer.flipX)
{
spriteRenderer.flipX = false;
}
else if (horizontal == -1 && !spriteRenderer.flipX)
{
spriteRenderer.flipX = true;
}
body.velocity = new Vector2(horizontal * speed, body.velocity.y);
animator.SetFloat("Speed", Mathf.Abs(horizontal));
float vertical = Input.GetAxisRaw("Vertical");
if (vertical == 1)
{
RaycastHit2D hit = Physics2D.Raycast(raycastPoint.transform.position, Vector2.down, 0.01f);
if (hit.collider != null)
{
body.AddForce(new Vector2(0f, jump));
}
}
}
}
For now I have achieved the right and left movements.
For the jump, I have a child gameobject just under the player and I'm firing a raycast to the bottom so I can know if my player is grounded or not.
I have two problems.
PROBLEM NUMBER ONE.
Sometimes I feel like my "AddForce" line is executed multiple times my player is jumping really high
Problem number one image
PROBLEM NUMBER TWO.
When I'm jumping to the left or right wall, if I keep pressing the left or right key my player is not falling anymore and stay against the wall.
Problem number two image
I tried to put my code into the FixedUpdate method (I know it's better) but I had the same results.
And I tried to set the Collision Detection on Continuous but I had the same results.
Try this code for your first problem :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Animator))]
public class Player_Controller : MonoBehaviour {
private Rigidbody2D body;
private bool canJump, facingRight;
private Animator anim;
[SerializeField]
private float moveSpeed, jumpForce;
void Start ()
{
SetStartValues();
}
void FixedUpdate ()
{
float horizontal = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", Mathf.Abs(horizontal));
Flip(horizontal);
Move(horizontal);
Jump();
}
private void SetStartValues()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
canJump = true;
facingRight = true;
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
body.AddForce(new Vector2(0, jumpForce));
canJump = false;
}
}
private void Move(float x)
{
body.velocity = new Vector2(x * moveSpeed * Time.deltaTime, body.velocity.y);
}
private void Flip(float x)
{
if (x > 0 && !facingRight|| x < 0 && facingRight)
{
facingRight = !facingRight;
transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y) ;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
canJump = true;
}
}
}
And don't forget to put the "Ground" tag on your ground object.