Character Stopped Moving and I Don't Know Why - c#

I had my code working perfectly the character was moving side to side and jumping but I tried to get him to stop jumping twice and he just stopped moving entirely. Can you help me figure out what I did wrong? I have looked this question up but yet to find an answer that makes sense to me (I'm relatively new) so if some can work through this with me I would appreciate it greatly so I can get back to work learning.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
bool jumpKeyWasPressed;
float horizontalInput;
Rigidbody rigidBodyComponent;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
rigidBodyComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//Space key input
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
}
//main problem I think
void FixedUpdate ()
{
if (!isGrounded)
{
return;
}
if (jumpKeyWasPressed)
{
rigidBodyComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
rigidBodyComponent.velocity = new Vector3(horizontalInput,rigidBodyComponent.velocity.y, 0);
}
void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}

If isGrounded is false, you return right out of the function. The last line is also skipped this way. To fix this, you could simply check if isGrounded is true, and only execute the jumping code then (forget return).
if (isGrounded) {
if (jumpKeyWasPressed) {
// ...
}
}

Related

Force on horizontal movement on unity 2D character controller is not working correctly

C# Character Controller
I'm new to using unity and I having difficulty with the force being applied to the sprite. The jump vector 2 variable is fine but I'm having issue with the horizontal movement. The code is not detecting if the key is held down,it will only add force to either side if you constantly tap the key, then it will move in a direction.
I'm not sure if I cant use the rigid body for horizontal movement or the vector is not written correctly. If you could please respond with the possible issues and or solution that would be helpful, thanks.
public float JumpForce;
public float HorizontalForce;
bool isGrounded = false;
Rigidbody2D RB;
void Start()
{
RB = GetComponent<Rigidbody2D>();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
if(isGrounded == true)
{
RB.AddForce(Vector2.up * JumpForce);
isGrounded = false;
}
}
if (Input.GetKeyDown(KeyCode.A))
{
RB.AddForce(Vector2.left * HorizontalForce);
}
if (Input.GetKeyDown(KeyCode.D))
{
RB.AddForce(Vector2.right * HorizontalForce);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ground")) ;
{
if(isGrounded == false)
{
isGrounded = true;
}
}
}
}
You need GetButton() instead of GetButtonDown().
GetButtonDown is only true for a single frame, in which the button was pressed. GetButton returns true as long as you hold the button

When I press space, my character doesn't always jump in my Unity2D project

https://www.youtube.com/watch?v=gB1F9G0JXOo&t=11865s
I'm watching this tutorial and I did everything the same as the guy in the video did until the "Player Jumping" part, when his character can jump whenever he presses the space button, but for me it doesn't work the same way. Can somebody help or tell me what is the problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField]
private float moveForce = 10f;
[SerializeField]
private float jumpForce = 11f;
private float movementX;
private Rigidbody2D myBody;
private SpriteRenderer sr;
private Animator anim;
private string WALK_ANIMATION = "Walk";
private void Awake()
{
myBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
PlayerMoveKeyboard();
AnimatePlayer();
}
private void FixedUpdate()
{
PlayerJump();
}
void PlayerMoveKeyboard()
{
movementX = Input.GetAxisRaw("Horizontal");
transform.position += new Vector3(movementX, 0f, 0f) * moveForce * Time.deltaTime;
}
void AnimatePlayer()
{
// we are going to the right side
if (movementX > 0)
{
anim.SetBool(WALK_ANIMATION, true);
sr.flipX = false;
}
// we are going to the left side
else if (movementX < 0)
{
anim.SetBool(WALK_ANIMATION, true);
sr.flipX = true;
}
else
{
anim.SetBool(WALK_ANIMATION, false);
}
}
void PlayerJump()
{
if (Input.GetButtonDown("Jump"))
{
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
} // class
Try moving your jump function from the FixedUpdate into the normal Update Function.
That should fix it.
Update gets called every frame and thus captures every input while FixedUpdate gets called in a fixed offset to update the physics logic of the engine. Now when you are looking for keyboard input, you want to always do that in Update, never in FixedUpdate because you'll miss input that was given to the player between the fixed update frames.
But since you want to do physics related changes only in FixedUpdate, you want to split the code between the two methods.
bool shouldJump = false;
void Update()
{
if (Input.GetButtonDown("Jump"))
shouldJump = true;
}
void FixedUpdate()
{
if (shouldJump)
{
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
shouldJump = false;
}
}
I have looked into the code in the video and he does the jump-logic in FixedUpdate. It seems weird to me and this is definitely bad practice. But one of the comments below addresses your issue as well and proposes a similar solution.

3dCharacter in Unity Continues jumping in the air

Im trying to follow Imphenzia's youtube tutorial on Unity3d and i've basically followed his code to a tee (1:28:00 in the following video) and my character continues to jump in the air. Not sure what im missing here and its driving me crazy.
The video - https://www.youtube.com/watch?v=pwZpJzpE2lQ&t=5342s&ab_channel=Imphenzia
the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private bool jumpKeyWasPressed;
private float horizontalInput;
private Rigidbody rigidBodyComponent;
private bool isGrounded;
// Start is called before the first frame update
void Start()
{
rigidBodyComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
}
//Fixed update is called once every physics update
private void FixedUpdate()
{
if (isGrounded != true) //if (isGrounded == false) works too
{
return;
}
if (jumpKeyWasPressed)
{
rigidBodyComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
rigidBodyComponent.velocity = new Vector3(horizontalInput, rigidBodyComponent.velocity.y, 0);
}
private void OnCollisionEnter(Collision collision)
{
// use ' collision. ' toget^^info using ^^^^^
isGrounded = true;
}
}
I was simply missing the line of code - private void OnCollisionExit. but he answers that later on, and removes the code that was written. my bad!

How to allow to jump only once in Unity2D

Hey Guys im Currently working on an 2D Endlessrunner and i need help, i want to only jump once until the character touches the ground again could anyone help me please i would be very thankfull
heres the code for the character :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dino : MonoBehaviour
{
bool isJumping;
Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
isJumping = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("space"))
{
rb.velocity = new Vector3(0, 20, 0);
isJumping = true;
}
}
}
Add the is jumping condition to your jump code like this:
// Update is called once per frame
void Update()
{
if (Input.GetKey("space") && !isJumping)
{
rb.velocity = new Vector3(0, 20, 0);
isJumping = true;
}
}
And handle the isJumping boolean in the collision logic of your character with the ground. You can keep a reference to the floor collider to check if whats dino is colliding with is the floor:
public collider2D floorCol; //attach in unity editor
OnCollisionEnter2D(Collision2D collision) {
//check you are colliding with the floor
if (collision.collider == floorCol)
isJumping = false;
}
assuming 2d for simplicity's sake.

How can i detect if a character is already inside another gameobject?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour {
enum MoveProperties
{
DirectionStart,
DirectionEnd
};
public float spinSpeed = 2.0f;
private bool rotate = false;
private bool exited = false;
private List<GameObject> prefabs;
private void Start()
{
InstantiateObjects gos = GetComponent<InstantiateObjects>();
prefabs = new List<GameObject>();
prefabs = gos.PrefabsList();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player entered the hole");
rotate = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
Debug.Log("Player exited the hole");
rotate = false;
exited = true;
}
}
void Rotate()
{
if (rotate)
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
spinSpeed += 1f;
}
if (rotate == false && exited == true)
{
transform.Rotate(Vector3.up, spinSpeed * Time.deltaTime);
if (spinSpeed > 0.0f)
spinSpeed -= 1f;
}
}
private void Update()
{
Rotate();
}
}
There are two triggers here:
OnTriggerEnter and OnTriggerExit.
But this triggers will work if the character first went out and then went in again. Or went out. But i need to detect while the character is already inside.
Without first going out and getting in again.
The situation is that the character is first in one place(hole inside a object) and then i change the character position to another object with hole. After changing the position i need to detect somehow that the character is inside the second hole.
But this triggers will work if the character first went out and then
went in again. Or went out. But i need to detect while the character
is already inside. Without first going out and getting in again.
You are looking for the OnTriggerStay function. As long as both Colliders are inside one another, OnTriggerStay will always be called every frame.
void OnTriggerStay(Collider other)
{
}
There is also OnCollisionStay if you decide to use Collision instead of a trigger.
void OnCollisionStay(Collision collisionInfo)
{
}

Categories

Resources