Untitled
I need to write a code for a 2d side scroller indie game in unity, can you write me a code where my player can move, jump, double jump, dash and attack? Also keep in mind that I have sprites and I flip the character for each movementunknown
csharp
9 months ago
3.4 kB
2
Indexable
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Movement variables
public float moveSpeed = 5f;
public float jumpForce = 10f;
public float doubleJumpForce = 7f;
public float dashDistance = 3f;
public float dashDuration = 0.3f;
public float attackCooldown = 0.5f;
private float attackTimer = 0f;
private bool isFacingRight = true;
// Jumping variables
private bool isGrounded = false;
private bool canDoubleJump = false;
private bool isJumping = false;
private bool isDashing = false;
// Component references
private Rigidbody2D rb;
private Animator animator;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
private void Update()
{
// Flip sprite if necessary
if (rb.velocity.x > 0 && !isFacingRight)
{
Flip();
}
else if (rb.velocity.x < 0 && isFacingRight)
{
Flip();
}
// Jumping logic
if (Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
isJumping = true;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
animator.SetTrigger("Jump");
}
else if (canDoubleJump)
{
isJumping = true;
canDoubleJump = false;
rb.velocity = new Vector2(rb.velocity.x, doubleJumpForce);
animator.SetTrigger("Jump");
}
}
// Dashing logic
if (Input.GetButtonDown("Dash") && !isDashing)
{
isDashing = true;
rb.velocity = new Vector2(transform.localScale.x * dashDistance / dashDuration, rb.velocity.y);
animator.SetTrigger("Dash");
Invoke("StopDash", dashDuration);
}
// Attack logic
if (Input.GetButtonDown("Fire1") && attackTimer <= 0)
{
attackTimer = attackCooldown;
animator.SetTrigger("Attack");
}
attackTimer -= Time.deltaTime;
}
private void FixedUpdate()
{
// Horizontal movement logic
float moveInput = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);
// Check if grounded
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, 0.6f);
if (hit.collider != null)
{
isGrounded = true;
canDoubleJump = true;
isJumping = false;
}
else
{
isGrounded = false;
}
// Update animator parameters
animator.SetBool("Grounded", isGrounded);
animator.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
animator.SetBool("Jumping", isJumping);
animator.SetBool("Dashing", isDashing);
}
private void Flip()
{
isFacingRight = !isFacingRight;
transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
}
private void StopDash()
{
isDashing = false;
rb.velocity = new Vector2(0f, rb.velocity
Editor is loading...
Leave a Comment