0% found this document useful (0 votes)
4 views2 pages

PlayerBehavior Fri

The document contains a Unity C# script for player behavior in a game, defining movement, rotation, and jumping mechanics. It utilizes Rigidbody and CapsuleCollider components to manage physics interactions and checks if the player is grounded before allowing jumps. The script processes input for movement and rotation in the Update and FixedUpdate methods, ensuring smooth gameplay.

Uploaded by

cookiesntacos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

PlayerBehavior Fri

The document contains a Unity C# script for player behavior in a game, defining movement, rotation, and jumping mechanics. It utilizes Rigidbody and CapsuleCollider components to manage physics interactions and checks if the player is grounded before allowing jumps. The script processes input for movement and rotation in the Update and FixedUpdate methods, ensuring smooth gameplay.

Uploaded by

cookiesntacos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

using System.

Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBehavior : MonoBehaviour


{
public float MoveSpeed = 10f;
public float RotateSpeed = 75f;
public float JumpVelocity = 5f;
public float DistanceToGround = 0.1f;
public LayerMask GroundLayer;

private float _vInput;


private float _hInput;
private Rigidbody _rb;
private CapsuleCollider _col;
private bool _isJumping;

void Start()
{
_rb = GetComponent<Rigidbody>();
_col = GetComponent<CapsuleCollider>();
}

void Update()
{
_vInput = Input.GetAxis("Vertical") * MoveSpeed;
_hInput = Input.GetAxis("Horizontal") * RotateSpeed;

_isJumping |= Input.GetKeyDown(KeyCode.Space)

this.transform.Translate(Vector3.forward * _vInput * Time.deltaTime);


this.transform.Rotate(Vector3.up * _hInput * Time.deltaTime);

void FixedUpdate()
{
if (IsGrounded() && _isJumping)
{
_rb.AddForce(Vector3.up * JumpVelocity, ForceMode.Impulse);
}

Vector3 rotation = Vector3.up * _hInput;


Quaternion angleRot = Quaternion.Euler(rotation *Time.fixedDeltaTime);

_rb.MovePosition(this.transform.position + this.transform.forward *
_vInput * Time.fixedDeltaTime);
_rb.MoveRotation(_rb.rotation * angleRot);

_isJumping = false
}

private bool IsGrounded()


{
Vector3 capsuleBottom = new Vector3(_col.bounds.center.x,
_col.bounds.min.y, _col.bounds.center.z);
bool grounded = Physics.CheckCapsule(_col.bounds.center, capsuleBottom,
DistanceToGround, GroundLayer, QueryTriggerInteraction.Ignore);

return grounded;
}
}

You might also like