I am making a 2D battle platformer, and I would like to add diving, but it seems really hard, as I am pretty new to coding. I watched some videos, but none of them were what I was looking for. I decided to leave it up to the professionals. Here’s my code what I want is the player to launch in the direction they’re facing, and to launch up in the air at the same height as jumping.
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
//Variables
[Header("Movement")]
//Input Variables
public float playerSpeed = 5f;
public float jumpheight = 5f;
private int extraJumps;
public int extraJumpsValue = 1;
[Header("Physics")]
//Physics stuff
public LayerMask ground;
public Rigidbody2D rb;
public Transform player;
bool isGrounded;
public Transform groundCheck;
[Header("Animation")]
//Animation
private bool facingRight;
public Animator anim;
public ParticleSystem jumpParticles;
[Header("Sounds")]
public AudioSource audioSource;
public float Volume;
//Start Function
void Start()
{
extraJumps = extraJumpsValue;
audioSource.volume = Volume;
}
//Moving
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.5f, ground);
float x = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(x * playerSpeed, rb.velocity.y);
if (facingRight == true && x > 0)
{
Flip();
}
else if (facingRight == false && x < 0)
{
Flip();
}
}
//Jumping
void Update()
{
anim.SetFloat("Horizontal", rb.velocity.x);
anim.SetFloat("Speed", rb.velocity.sqrMagnitude);
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (Input.GetButtonDown("Jump") && extraJumps > 0)
{
rb.velocity = Vector2.up * jumpheight;
extraJumps--;
//Particles
jumpParticles.Play();
//Sounds
FindObjectOfType<AudioManager>().Play("Jump");
}
else if (Input.GetButtonDown("Jump") && isGrounded == true)
{
rb.velocity = Vector2.up * jumpheight;
}
DidIDie();
Attack();
}
//Flips the player
void Flip()
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
//Checks if player has died
void DidIDie()
{
if(player.position.y <= -10f)
{
transform.position = new Vector3(0f, 0f, 0f);
}
}
}
Thanks in advance
Also It should be physics based, as the game is entirely built on physics.