jittery movement while jumping unity 2d - c#

i am using a 2 scripts, a player movement and a camera follow script. while jumping normally the jump is smooth, it is also smooth while moving my character. what i understand is that the camera follow script is somehow not allowing the jump to be smooth.here is the player movement script.
public class player_movement : MonoBehaviour
{
Rigidbody2D rb;
public float speed;
private float moveInput;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask whatIsGround;
public float jumpForce;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
private Animator anim;
void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
movement();
}
private void movement()
{
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (isGrounded == false && moveInput == 0)
{
anim.SetBool("is running", false);
}
else if (isGrounded == true && moveInput != 0)
{
anim.SetBool("is running", true);
}
else if(isGrounded == true && moveInput == 0)
{
anim.SetBool("is running", false);
}
else if (isGrounded == false && moveInput != 0)
{
anim.SetBool("is running", false);
}
}
void Update()
{
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround);
if (moveInput > 0)
{
transform.eulerAngles = new Vector2(0, 0);
}
else if (moveInput < 0)
{
transform.eulerAngles = new Vector2(0, 180);
}
Jump();
}
private void Jump()
{
if (isGrounded == true && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpForce;
}
if (Input.GetKey(KeyCode.Space))
{
if (jumpTimeCounter > 0 && isJumping == true)
{
rb.velocity = Vector2.up * jumpForce;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
private void LateUpdate()
{
//Jump();
}
}
and here is the camera follow script.
public class cammeraFollow : MonoBehaviour
{
public GameObject followObject;
public Vector2 followOffset;
public float speed = 3f;
private Vector2 threshold;
private Rigidbody2D rb;
void Start()
{
threshold = calculateThreshold();
rb = followObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
Vector2 follow = followObject.transform.position;
float xDifference = Vector2.Distance(Vector2.right * transform.position.x, Vector2.right * follow.x);
float yDifference = Vector2.Distance(Vector2.up * transform.position.y, Vector2.up * follow.y);
Vector3 newPosition = transform.position;
if(Mathf.Abs(xDifference) >= threshold.x)
{
newPosition.x = follow.x;
}
if (Mathf.Abs(yDifference) >= threshold.y)
{
newPosition.y = follow.y;
}
float moveSpeed = rb.velocity.magnitude > speed ? rb.velocity.magnitude : speed;
transform.position = Vector3.MoveTowards(transform.position, newPosition, moveSpeed * Time.deltaTime);
}
private Vector3 calculateThreshold()
{
Rect aspect = Camera.main.pixelRect;
Vector2 t = new Vector2(Camera.main.orthographicSize * aspect.width / aspect.height, Camera.main.orthographicSize);
t.x -= followOffset.x;
t.y -= followOffset.y;
return t;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Vector2 border = calculateThreshold();
Gizmos.DrawWireCube(transform.position, new Vector3(border.x * 2, border.y * 2, 1));
}
}
can anyone help me with this one.

FixedUpdate is not called every frame but in fixed intervals instead. It's more for physics and gameplay code.
Try changing the camera follow script to Update.

Related

I would like to know how to get Unity joystick values

I don't know how to make player move from joystick in Unity 2D.
[SerializeField] private float speed;
private Rigidbody2D rb;
private Animator anim;
private bool grounded;
private void Awake()
{
Time.timeScale = 1;
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
Move();
}
private void Move()
{
//Move
float horizontalInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(horizontalInput * speed, rb.velocity.y);
//Flip
if (horizontalInput > 0f)
{
transform.localScale = new Vector3(6, 6, 6);
}
else if (horizontalInput < 0f)
{
transform.localScale = new Vector3(-6, 6, 6);
}
anim.SetBool("run", horizontalInput != 0);
anim.SetBool("grounded",grounded);
}
private void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
grounded = true;
}
else if (col.gameObject.tag == "Skill")
{
grounded = true;
Destroy(col.gameObject,5f);
}
}
This is code I want to modify to get the joystick. It's not complete as I still don't know how to use joystick in code.

Flickering IsGrounded function

IsGrounded Function started flickering when I added OBJs to my project. It was working perfectly before I started working on it today it only started after I added some material and OBJS. I tried reverting to the state it was in before I added different elements but the problem still happened. It always occurs after about 30 seconds of running the game in the window. How can I fix this?
\using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//VARIABLES
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
public float _speed = 10;
public float _rotationSpeed = 180;
private Vector3 moveDirection;
private Vector3 Velocity;
private Vector3 rotation;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
//REFERNCES
private CharacterController controller;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
Move();
this.rotation = new Vector3(0, Input.GetAxisRaw("Horizontal") * _rotationSpeed * Time.deltaTime, 0);
Vector3 move = new Vector3(0, 0, Input.GetAxisRaw("Vertical") * Time.deltaTime);
move = this.transform.TransformDirection(move);
controller.Move(move * _speed);
this.transform.Rotate(this.rotation);
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if (isGrounded && Velocity.y < 0)
{
Velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, moveZ);
if (isGrounded)
{
if (moveDirection != Vector3.zero && !Input.GetButtonDown("Fire3"))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetButtonDown("Fire3"))
{
Run();
}
else if (moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
controller.Move(moveDirection * Time.deltaTime);
Velocity.y += gravity * Time.deltaTime;
controller.Move(Velocity * Time.deltaTime);
}
private void Idle()
{
}
private void Walk()
{
moveSpeed = walkSpeed;
}
private void Run()
{
moveSpeed = runSpeed;
}
private void Jump()
{
Velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
}

how can I make the game object disappear?

when I was watching on YouTube, tutorials about endless runner on part 2, the game object wouldn't disappear when it hits the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.GetComponent<rocket>().health -= damage;
Debug.Log(other.GetComponent<rocket>().health);
Destroy(gameObject);
}
}
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class rocket : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;
public float speed;
public float maxHeight;
public float minHeight;
public int health = 3;
void Update()
{
if (health <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < maxHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}
else if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > minHeight)
{
targetPos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}
}
}
from this one https://www.youtube.com/watch?v=FVCW5189evI and I'm confused why it didn't work, can someone tell me what is wrong?
if you want to destroy use this, Correct Method to get the game object when collide is: other.gameObject
void onTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
Destory(other.gameObject);
}
}
public class megaStar : MonoBehaviour{
private Rigidbody2D rb;
private Animator _ani;
public bool canAttack = true;
[SerializeField] private Attack _attackObject;
private AudioSource _as;
public checkpoint lastCheckpoint;
public bool isDead = false;
private float _timer = 1.0f;
public float attackTimer = 2.0f;
public GameObject projectile;
public float projectileSpeed = 18.0f;
public Transform projectileAttackPoint;
public float timeDelayForNextShoot = 0.1f;
private float CONST_timeDelayForNextShoot;
// Start is called before the first frame update
void Start(){
CONST_timeDelayForNextShoot = timeDelayForNextShoot;
rb = GetComponent<Rigidbody2D>();
_as = GetComponent<AudioSource>();
_ani = GetComponent<Animator>();
_timer = attackTimer;
}
void Update(){
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(0f, 10f);
}
else if (Input.GetKey(KeyCode.S))
{
rb.velocity = new Vector2(0f, -10f);
}
else
{
rb.velocity = new Vector2(0f, 0f);
}
timeDelayForNextShoot -= Time.deltaTime;
if (Input.GetKeyDown(KeyCode.K) && timeDelayForNextShoot <= 0f){
_ani.SetBool("projectileAttack", true);
GameObject go = Instantiate(projectile, projectileAttackPoint.position, projectileAttackPoint.rotation) as GameObject;
go.GetComponent<Rigidbody2D>().velocity = new Vector2(-projectileSpeed, 0.0f);
Destroy(go, 2.0f);
timeDelayForNextShoot = CONST_timeDelayForNextShoot;
canAttack = false;
// new WaitForSeconds(1);
return;
}
}
void FixedUpdate()
{
if (!isDead)
{
Update();
}
else{
rb.velocity = Vector2.zero;
RigidbodyConstraints2D newRB2D = RigidbodyConstraints2D.FreezePositionY;
rb.constraints = newRB2D;
}
}
private void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.CompareTag("Enemy"))
{
GetComponent<HitPoints>().TakeDamage(1);
}
}
}
Use SetActive instead of Destroy Function.
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("rocket"))
{
//rocket takes damage 1
other.gameObject.GetComponent<rocket>().health -= damage;
Debug.Log(other.gameObject.GetComponent<rocket>().health);
gameObject.SetActive(false);// it'll Hide GameObject instead of Destroying
// gameObject.SetActive(true);// to show again
}
}

How can I replace characterScale.x = -1 with transform.Rotate (0f, 180f, 0f) in this context, without it being executed every frame?

I am very new to coding video games so I have been using a lot on online tutorials to assist me with making a basic platformer/shooter. In order for my character to be able to shoot in both directions, I need the sprite as well as it's child "FirePoint" to flip. How can I flip my character and it's children whenever the Horizontal value = -1 without the same command being executed every frame.
Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpforce;
private float moveInput;
private Rigidbody2D rb;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpsValue;
public Animator animator;
void Start()
{
extraJumps = extraJumpsValue;
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
void Update()
{
animator.SetFloat("Horizontal", moveInput);
if (Input.GetKeyDown(KeyCode.Space) && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpforce;
extraJumps--;
}
else if (Input.GetKeyDown(KeyCode.Space) && extraJumps == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpforce;
}
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
Vector3 characterScale = transform.localScale;
if (Input.GetAxisRaw("Horizontal") < 0)
{
characterScale.x = -1;
}
if (Input.GetAxisRaw("Horizontal") > 0)
{
characterScale.x = 1;
}
transform.localScale = characterScale;
}
}

How do I add running and animations to my player controller script?

I am new to Unity and have been having a hard time adding running and animations (I have the animations and they are set up in animator) to my FPS controller script. Can someone please help me add running and animations? I would be extremely grateful.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Animator anim;
float RotateX;
float RotateY;
public static bool GamePaused;
[SerializeField]
[Header("Game Objects")]
public GameObject Camera;
public GameObject PauseMenu;
public GameObject Player;
[Header("Movement Settings")]
public float WalkSpeed = 5.0f;
public float RunSpeed = 10.0f;
[Header("Rotation Settings")]
public float RorationSpeed;
public float MaxYAxis = 60.0f; // right
public float MinYAxis = -48.0f; // left
public bool Grounded;
private void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * WalkSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * WalkSpeed * Time.deltaTime);
RotateX += Input.GetAxis("Mouse X") * RorationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RorationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
}
Here is what I have to trigger the different animations in the animator, but the animation follows through when I release the key rather than switching immediately upon release.
if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.A) ||
Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D) ||
Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.LeftArrow) ||
Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalking", true);
}
if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyDown(KeyCode.A) ||
Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.D) ||
Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.LeftArrow) ||
Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalking", false);
}
What I can suggest is that you use the horizontal and vertical axes, rather than hard-coded key presses.
More specifically, first of all (if you have not already) in the animator window create an idle state and a walking animation state. You will need somehow to transition between the two states. To do that you will need to create a new bool parameter (let's name it "isWalking" as you did) and create a new condition between the idle and the walking state. For example, set to transition between "idle" to "walking" when isWalking is true and transition between "walking" to "idle" when isWalking is false.
Now in your PlayerController script in the update or fixed update you can add the following code
horizontalMovement = Input.GetAxis("Horizontal");
verticalMovement = Input.GetAxis("Vertical");
//normalize vector so movement in two axis simultanesly is balanced.
moveDirection = (horizontalMovement * transform.right + verticalMovement * transform.forward).normalized;
/* based on your code although a rigid body solution or character controller would have been more robust */
transform.Translate(moveDirection * WalkSpeed * Time.deltaTime);
if (horizontal != 0 || vertical != 0)
{
animator.setFloat("isWalking",true);
}
else
{
animator.setFloat("isWalking",false);
}
However this solution is working is implemented based on the code you provided. If you want to switch in a more robust and easy to maintain script you can use this free controller that uses a rigidbody and has animations already installed and working.
https://github.com/PanMig/First-Person-Unity-Camera
Here is my working script with walking, running, jumping and animation triggers.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
Animator anim;
float RotateX;
float RotateY;
Rigidbody rb;
public static bool GamePaused;
public bool isGrounded;
[SerializeField]
[Header("Game Objects")]
public GameObject Camera;
public GameObject PauseMenu;
public GameObject Player;
[Header("Movement Settings")]
public float DefaultSpeed = 5.0f;
public float WalkSpeed = 5.0f;
public float RunSpeed = 10.0f;
public float jumpForce = 2.5f;
public Vector3 jump;
[Header("Rotation Settings")]
public float RorationSpeed = 3.0f;
public float MaxYAxis = 60.0f;
public float MinYAxis = -48.0f;
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 1.0f, 0.0f);
}
void Update()
{
Rotation();
Movement();
Bool();
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
}
}
void Rotation()
{
RotateX += Input.GetAxis("Mouse X") * RorationSpeed;
RotateY += Input.GetAxis("Mouse Y") * RorationSpeed;
RotateY = Mathf.Clamp(RotateY, MinYAxis, MaxYAxis);
Camera.transform.localRotation = Quaternion.Euler(-RotateY, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, RotateX, 0f);
}
void Movement()
{
transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * WalkSpeed * Time.deltaTime);
transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * WalkSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.LeftShift))
{
WalkSpeed = RunSpeed;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
WalkSpeed = DefaultSpeed;
}
}
void Bool()
{
if (Input.GetKeyDown(KeyCode.W))
{
anim.SetBool("IsWalkingForward", true);
}
if (Input.GetKeyDown(KeyCode.A))
{
anim.SetBool("IsWalkingLeft", true);
}
if (Input.GetKeyDown(KeyCode.S))
{
anim.SetBool("IsWalkingBack", true);
}
if (Input.GetKeyDown(KeyCode.D))
{
anim.SetBool("IsWalkingRight", true);
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
anim.SetBool("IsWalkingForward", true);
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
anim.SetBool("IsWalkingLeft", true);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
anim.SetBool("IsWalkingBack", true);
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
anim.SetBool("IsWalkingRight", true);
}
if (Input.GetKeyUp(KeyCode.W))
{
anim.SetBool("IsWalkingForward", false);
}
if (Input.GetKeyUp(KeyCode.A))
{
anim.SetBool("IsWalkingLeft", false);
}
if (Input.GetKeyUp(KeyCode.S))
{
anim.SetBool("IsWalkingBack", false);
}
if (Input.GetKeyUp(KeyCode.D))
{
anim.SetBool("IsWalkingRight", false);
}
if (Input.GetKeyUp(KeyCode.UpArrow))
{
anim.SetBool("IsWalkingForward", false);
}
if (Input.GetKeyUp(KeyCode.LeftArrow))
{
anim.SetBool("IsWalkingLeft", false);
}
if (Input.GetKeyUp(KeyCode.DownArrow))
{
anim.SetBool("IsWalkingBack", false);
}
if (Input.GetKeyUp(KeyCode.RightArrow))
{
anim.SetBool("IsWalkingRight", false);
}
}
void OnCollisionStay()
{
isGrounded = true;
}
void OnCollisionExit()
{
isGrounded = false;
}
}

Categories