Unity GameProject

nananana·2022년 10월 18일
0

So started the basic setup for the game.
Currently not certain how I am going to take this.

Simple features learned in previous lessons were applied with a little bit of googling for details

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

public class MovingObject : MonoBehaviour
{
    public void Jump(int scale, Rigidbody rb){
        rb.AddForce(Vector3.up * scale, ForceMode.Impulse);
    }

    public void Roll(float h, float h_scale, float v, float v_scale, Rigidbody rb){
        Vector3 vec = new Vector3(h_scale * h, 0, v_scale * v);
        rb.AddForce(vec, ForceMode.Impulse);
    }
}

Code consist of two parts. Since I wanted to test out the object oriented programming nature I seperated the moving object and player object. This way I might add another moving object that is not a player using this object.

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


public class PlayerControl : MovingObject{
    bool IsJumpKeyPressed;
    bool IsGrounded;
    bool CanDoubleJump;
    public LayerMask GroundLayer;
    Rigidbody rb;
    void Start(){
        rb = GetComponent<Rigidbody>();
        IsJumpKeyPressed = false;
        IsGrounded = false;
        GroundLayer = LayerMask.GetMask("Ground");
    }
    void Update(){
        if(Input.GetButtonDown("Jump") & IsGrounded){
            IsJumpKeyPressed = true;
        }else if(Input.GetButtonDown("Jump") & CanDoubleJump){
            IsJumpKeyPressed = true;
            CanDoubleJump = false;
        }
        if(!CanDoubleJump & IsGrounded){
            CanDoubleJump = true;
        }
        Floor();
    }
    void FixedUpdate(){
        if(IsJumpKeyPressed){
            Jump(5, rb);
            IsJumpKeyPressed = false;
            // Debug.Log("jump!");
        }

        Roll(Input.GetAxis("Horizontal"), 0.5f, Input.GetAxis("Vertical"), 0.5f, rb);
    }
    private void Floor(){
        IsGrounded = Physics.CheckSphere(transform.position, 0.6f, GroundLayer);
    }
}

Second code is basically take input and gives player some motion.
I tried two things here. First I tried a double jump mechanism. I also trying to make sense of using Update() and FixedUpdate().

Not so sure if this is a suitable way of using it.

I tried Physics.CheckSphere() function to determine grounded state. As seen in the code it returns a boolean value. Original CheckSphere() function seem to detect collision within the given radius. Since, I reduced the choice to GroundLayer which I labeled and tagged the plane as Ground in unity and extracted it assigned it to variable GroundLayer. It seem to detect when the ground is 0.6 from the Playerobject.

Radius is 0.5 but I added 0.1 since I assume that floor calculations would lead to a 0.5 != 0.5 situation as they often do.

0개의 댓글