checking if grounded without using oncollision enter/exit? - c#

so I have a script that rotates a cube (by 90 degrees when a direction is pressed) currently im using the oncollision enter to detect walls and when I try to use it to also check if grounded then it will just completely stop everything when i leave one collision and enter another, or it won't fully check when im in mid air and will allow me to move when i don't want to be able to. Any and all help is greatly appreciated.
{
bool isGrounded = true;
private Rigidbody2D rb;
bool leftInput = true;
bool rightInput = true;
public float RollingDuration = 0.2f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// fixed update is for physics
void FixedUpdate()
{
var dir = Vector3.zero;
if (Input.GetKey(KeyCode.LeftArrow) && leftInput && isGrounded)
{
dir = Vector3.left;
}
if (Input.GetKey(KeyCode.RightArrow) && rightInput && isGrounded)
{
dir = Vector3.right;
}
if (dir !=Vector3.zero && !isRolling)
{
StartCoroutine(Roll(dir));
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
//check to see if our player is grounded
if (collision.gameObject.tag == "Grounded")
{
isGrounded = true;
}
if (collision.gameObject.tag == "LeftWall" || collision.gameObject.tag == "RightWall")
{
StopCoroutine("Roll");
if (collision.gameObject.tag == "LeftWall")
{
leftInput = false;
// we are grounded when touching walls
isGrounded = true;
}
if (collision.gameObject.tag == "RightWall")
{
rightInput = false;
// we are grounded when touching walls
isGrounded = true;
}
if (collision.gameObject.tag == null)
{
isGrounded = false;
}
else
{
isRolling = false;
rb.velocity = Vector2.zero;
rb.velocity = new Vector2(0.0f, 0.0f);
rb.angularVelocity = 0.0f;
rb.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 0.0f);
rb.rotation = 0.0f;
}
}
}
bool isRolling = false;
IEnumerator Roll(Vector3 direction)
{
if (direction == Vector3.right && isGrounded)
{
leftInput = true;
}
else if (direction == Vector3.left && isGrounded)
{
rightInput = true;
}
isRolling = true;
var rotAxis = Vector3.Cross(Vector3.up, direction);
var pivot = (rb.transform.position + Vector3.down * 0.5f) + direction * 0.5f;
var startRotation = rb.transform.rotation;
var endRotation = Quaternion.AngleAxis(90.0f, rotAxis) * startRotation;
var startPosition = rb.transform.position;
var endPosition = rb.transform.position + direction;
var rotSpeed = 90.0f / RollingDuration;
var t = 0.0f;
while (t < RollingDuration && isGrounded)
{
t += Time.deltaTime;
if (t < RollingDuration && isGrounded)
{
rb.transform.RotateAround(pivot, rotAxis, rotSpeed * Time.deltaTime);
yield return null;
}
else
{
rb.transform.rotation = endRotation;
rb.transform.position = endPosition;
}
}
isRolling = false;
}
}

I think the most simple and common way to do ground checks is with casting a ray. So just cast a ray into the direction you want to check or try Overlap functions.
Example:
if(Physics.OverlapCircle(point, radius, layerMask)) {
//do stuff
}
So just cast a ray in all direction you want to check or add a overlap function to each side of the cube.

Related

Player's Dash abilty not isnt working correctly

I don't know how to make my character dash without it keeps ignoring the cooldown and the dash distance is small. I have been stumped on this for a long time and i want to continue with other things in my game but this has been stopping me. I use Unity and C#.
Here's my code:
public class PlayerMove : MonoBehaviour
{
private Rigidbody2D rb;
private BoxCollider2D bc;
private static bool isRunning;
private static bool isMoving;
private static bool isDashing;
private static bool isOnWall;
private static bool cooldown;
private static bool jumpCooldown;
private float time = 4f;
private float dashingspeed = 14f;
private float timewhiledashing = 2f;
private Vector2 dashingDir;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
bc = GetComponent<BoxCollider2D>();
cooldown = false;
}
// Update is called once per frame
private void Update()
{
bool IsGrounded()
{
float extraHeightText = .01f;
RaycastHit2D raycastHit = Physics2D.Raycast(bc.bounds.center, Vector2.down, bc.bounds.extents.y + extraHeightText);
Color rayColor;
if (raycastHit.collider != null)
{
rayColor = Color.green;
}
else
{
rayColor = Color.red;
}
Debug.DrawRay(bc.bounds.center, Vector2.down * (bc.bounds.extents.y + extraHeightText));
return raycastHit.collider != null;
}
float dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * 4f, rb.velocity.y);
isMoving = true;
float dirY = Input.GetAxisRaw("Vertical");
if (Input.GetKey("left ctrl"))
isRunning = true;
else
{
isRunning = false;
}
if (Input.GetKeyDown("left shift") && cooldown == false)
isDashing = true;
else
{
isDashing = false;
}
if (IsGrounded() && Input.GetButtonDown("Jump"))
{
rb.velocity = new Vector2(rb.velocity.x, 8f);
}
if (isRunning == true && isMoving == true)
{
rb.velocity = new Vector2(dirX * 6f, rb.velocity.y);
}
if (isDashing == true && cooldown == false)
{
dashingDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (dashingDir == new Vector2(0f,0f))
{
dashingDir = new Vector2(transform.localScale.x, 0f);
}
}
if (isDashing == true)
{
rb.velocity = dashingDir.normalized * dashingspeed;
return;
}
if (isDashing == true)
{
timewhiledashing -= 1 * Time.deltaTime;
}
if (timewhiledashing == 0f)
{
cooldown = true;
}
if (IsGrounded())
{
cooldown = false;
}
if (cooldown == true)
{
isDashing = false;
time -= 1 * Time.deltaTime;
}
if (time == 0f)
{
cooldown = false;
time = 4f;
timewhiledashing = 2f;
}
}
}
Please help me with this.
The reason your code is not dashing is because it detects if you get the key down, and if not it will be true again. So if you press the key, it will be true, then next frame it will be false.
This way, time while dashing will only go down for one frame.
Instead, you should use
if (Input.GetKey(KeyCode.LeftShift))

The enemy flies through the walls

I wrote a code for an enemy that, when he sees my character, will chase him. But when he sees my character and chases him, he goes through objects.There is a box collider 2D on it, but it moves with it. I've already tried everything, I don't know how to fix it. Can you please help fix
Here is my code:
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
idleSpeed = speed;
barDelta = Vector3.Distance(parent.position, barPoint.position);
bar = UIManager.AddEnemy(this);
}
void Update()
{
if (Vector2.Distance(transform.position, point.position) < positionOfPatrol && angry == false)
{
idle = true;
}
if (Vector2.Distance(transform.position, player.position) < stoppingDistance)
{
angry = true;
idle = false;
goBack = false;
}
if (Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
goBack = true;
angry = false;
}
if (idle == true)
{
Idle();
}
else if (angry == true)
{
Angry();
}
else if (goBack == true)
{
GoBack();
}
}
void Idle()
{
if (transform.position.x > point.position.x + positionOfPatrol)
{
moveingRight = false;
}
else if (transform.position.x < point.position.x - positionOfPatrol)
{
moveingRight = true;
}
if (moveingRight)
{
if (!facingRight) Flip();
facingRight = true;
transform.position = new Vector2(transform.position.x + speed * Time.deltaTime, transform.position.y);
}
else
{
if (facingRight) Flip();
facingRight = false;
transform.position = new Vector2(transform.position.x - speed * Time.deltaTime, transform.position.y);
}
}
void Angry()
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
speed = idleSpeed + 1;
}
void GoBack()
{
transform.position = Vector2.MoveTowards(transform.position, point.position, speed * Time.deltaTime);
speed = idleSpeed;
}
}
You should try to use a rigidbody with the collider. The collider does not actually do physics, that is what the rigidbody is for. If you add a rigidbody and set its velocity instead of setting the transform's position, it will not only detect collisions with walls but it will stop moving and do all of the physics you would expect.

Why does my script make my "dash" have a seemingly random duration and how can I fix it?

I am new to coding. I've been trying to Frankenstein basic tutorials into something of my own and it seems ive finally hit a wall. I'm really not sure what is causing this and would like some help to weed out the problem.
at the moment when I press the dash button (left shift) my character dashes in the direction he is facing but for a random duration. I would like it to be consistent and working properly.
Thanks in advance!
PS: Sorry for the long script, it contains everything to do with player movment.
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class CharacterController : MonoBehaviour
{
//Player Movement
public float speed;
public float jumpForce;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public float dashSpeed;
public float startDashTime;
public float dashCooldownTime = 2;
private float nextFireTime = 0;
public Animator animator;
private Rigidbody2D rb;
private float moveInput;
private bool isGrounded;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private float dashTime;
public int direction;
void Start()
{
animator.GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
dashTime = startDashTime;
}
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
if (direction < 1 )
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
// Dashing
if (Time.time > nextFireTime)
{
if (direction == 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
UnityEngine.Debug.Log("beaners");
nextFireTime = Time.time + dashCooldownTime;
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
}
else
{
if(dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
}
else
{
dashTime -= Time.deltaTime;
}
}
}
void Dashleft()
{
direction = 1;
rb.velocity = Vector2.left * dashSpeed;
}
void DashRight()
{
direction = 1;
rb.velocity = Vector2.right * dashSpeed;
}
}
Random duration is because of the use of Rigidbody2D.
See in Unity Rigidbody2D is responsible for each and every single physical interaction. It mean forces from player like player movement and forces from your environment like friction and collision.
Here what is happening is that when your player is dashing there is also player movement force, which is also applied on your player's Rigidbody2d. And friction of ground on which your player is running/dashing on.
I've added a comment on parts that I've changed.
Updated part of your script:
private bool isDashing;
.
.
.
void Update()
{
//Added: putting a Condition to check if you player is not dashing, if it is then
//player won't be able to do anything, As I've scene and done in many games. if you
//don't want this remove it and see what happens, this is not tested so sorry if there
//is something that is not working as intended.
//dashing condition check
if(!isDashing)
{
// Moving
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector3(0, 0, 0);
animator.SetBool("Moving", true);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector3(0, 180, 0);
animator.SetBool("Moving", true);
}
else
{
animator.SetBool("Moving", false);
}
// Jumping
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger("IsJumping");
isJumping = true;
jumpTimeCounter = jumpTime;
//Changed: use Add force method instead of changing the velocity.
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
//rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space) && isJumping == true)
{
if (jumpTimeCounter > 0)
{
//Changed: Same this rb.AddForce...
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
//rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
if (isGrounded == false)
{
animator.SetBool("Grounded", false);
}
if (isGrounded == true)
{
animator.SetBool("Grounded", true);
}
}
//dashing condition ends
// Dashing
if (Time.time > nextFireTime)
{
//Here your Dash timer ends.
isDashing = false;
if (direction == 0)
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
UnityEngine.Debug.Log("beaners");
nextFireTime = Time.time + dashCooldownTime;
//Here your Dash timer Starts.
isDashing = true;
if ((transform.rotation.eulerAngles.y == 180))
{
Dashleft();
}
else
{
DashRight();
}
}
}
}
else
{
if(dashTime <= 0)
{
direction = 0;
dashTime = startDashTime;
}
else
{
dashTime -= Time.deltaTime;
}
}
}
visit Unity - Scripting API: Rigidbody2D.AddForce hope it helps.
Happy Coding

Unity Tag and Collider problem while player is jumping

This is my player's jump code:
void Update()
{
float oldmoveHorizontal = moveHorizontal;
moveHorizontal = Joystick.Horizontal;
moveVertical = Joystick.Vertical;
if (isJumping == false && moveVertical >= .7f)
{
moveVertical = Speed * 70;
isJumping = true;
}
ball_move = new Vector2(moveHorizontal, moveVertical);
ball_rigid.AddForce(ball_move);
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
isJumping = false;
}
}
}
When ball touches under of the collider it can jump again. How can i block this situation ?
if you cant download: https://ibb.co/yVgXmrM
One solution is to check the position of the collision points of the collision and see any of them is "low enough" from the center of your player to be a jumpable collision:
private Collider2D playerCollider;
private float playerJumpableOffset = 0.001;
void Start() { playerCollider = GetComponent<Collider2D>(); }
void OnCollisionEnter2D(Collision2D col)
{
float jumpableWorldHeight = transform.position.y - playerJumpableOffset;
for (int i = 0 ; i < col.contactCount && isJumping; i++)
{
Vector2 contactPoint = col.GetContact(i).point;
if (contactPoint.y <= jumpableWorldHeight)
{
isJumping = false;
}
}
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
foreach (ContactPoint2D item in col.contacts)
{
Debug.Log("Normal:" + item.normal);
if (item.normal.y > 0 && col.gameObject.tag == "Ground")
{
isJumping = false;
Debug.Log("Top of Collider");
}
}
}}
I found my solution with checking top side of collider.
With this code way, if player touchs top side of collider, it's going to activate jump again.

Crouching issues in Unity

So I've created crouching in Unity 2D game, everything goes well except when there is something above the character after exiting crouching, what it does is that it returns to idle animation and decreases Y-axis position, I know that is normal but how can I keep the character crouched when there is something above him or when I hold the ctrl button? Check the script down below if necessary. Thanks!
private Rigidbody2D rb2d;
private float h = 0.0f;
public float Speed, Jump;
private bool canJump;
private Animator anim;
private BoxCollider2D bc2d;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
bc2d = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
h = Input.GetAxisRaw("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(h));
transform.Translate(Vector3.right * h * Speed * Time.deltaTime);
if (h != 0.0f)
{
transform.localScale = new Vector2(h, transform.localScale.y);
}
if (Input.GetKeyDown(KeyCode.Space) && canJump == true)
{
rb2d.AddForce(new Vector2(rb2d.velocity.x, Jump));
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
bc2d.enabled = false;
Speed = Speed / 2;
anim.SetBool("Crouch", true);
}
else if (Input.GetKeyUp(KeyCode.LeftControl))
{
bc2d.enabled = true;
Speed = Speed * 2;
anim.SetBool("Crouch", false);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "Ground")
{
canJump = true;
anim.SetBool("Jump", false);
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.name == "Ground")
{
canJump = false;
anim.SetBool("Jump", true);
}
}
Use RaycastHit2D. Basically before "standing" cast a ray Vector2.up from the character and if it hits, check to make sure there's enough room to stand. Something like:
private Rigidbody2D rb2d;
private Transform t;
private float h = 0.0f;
public float Speed, Jump;
private bool canJump;
private Animator anim;
private BoxCollider2D bc2d;
// Variable to check if character is attempting to stand
private bool tryingToStand = false;
// Keep crouching state
private bool isCrouching = false;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
bc2d = GetComponent<BoxCollider2D>();
t = GetComponent<Transform>();
}
// Update is called once per frame
void Update()
{
h = Input.GetAxisRaw("Horizontal");
anim.SetFloat("Speed", Mathf.Abs(h));
transform.Translate(Vector3.right * h * Speed * Time.deltaTime);
if (h != 0.0f)
{
transform.localScale = new Vector2(h, transform.localScale.y);
}
// Make sure we can jump and we're not crouching before jumping
if (Input.GetKeyDown(KeyCode.Space) && canJump == true && !isCrouching)
{
rb2d.AddForce(new Vector2(rb2d.velocity.x, Jump));
}
if (Input.GetKeyDown(KeyCode.LeftControl))
{
bc2d.enabled = false;
anim.SetBool("Crouch", true);
// Make sure we haven't already halved the speed
if (!tryingToStand)
{
Speed = Speed / 2;
}
// Set tryingToStand to false in case player holds ctrl before character has stood up
tryingToStand = false;
// Set crouching state to true
isCrouching = true;
}
else if (Input.GetKeyUp(KeyCode.LeftControl))
{
tryingToStand = true;
}
if (tryingToStand && CanStand())
{
tryingToStand = false;
// Set crouching state to false;
isCrouching = false;
bc2d.enabled = true;
Speed = Speed * 2;
anim.SetBool("Crouch", false);
}
}
bool CanStand()
{
RaycastHit2D hit = Physics2D.Raycast(t.position, Vector2.up);
if (hit.collider != null)
{
// Check the distance to make sure the character has clearance, you'll have to change the 1.0f to what makes sense in your situation.
if (hit.distance <= 1.0f)
{
return false;
}
}
return true;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.name == "Ground")
{
canJump = true;
anim.SetBool("Jump", false);
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.name == "Ground")
{
canJump = false;
anim.SetBool("Jump", true);
}
}

Categories

Resources