Rehber Unity C# first person controller script

Bu konuyu okuyanlar

ozmen_celik

Software Developer
Katılım
3 Mart 2012
Mesajlar
571
Reaksiyon puanı
318
Puanları
63
Yaş
39
Herkese merhabalar geçen ay içinde bir kaç kişi bana özel mesaj ile mouse ( x,y ) ve klavye hareket ( h,v ) nasıl yaparız diye sormuştu. Burdan paylaşarak cevap vereyim dedim ihtiyacı olanda yararlanabilsin diye.
İşinizi görmesi dileği ile.

Mouse Controller

C#:
public float mouseSensitivity=100f;

    public Transform playerBody;

    float xRotation = 0f;
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity *Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity *Time.deltaTime;

        xRotation -=mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

         transform.localRotation= Quaternion.Euler(xRotation, 0f, 0f);

        playerBody.Rotate(Vector3.up * mouseX);
    }

Player Controller

C#:
public CharacterController controller;

    public float speed= 12f;
    public float gravity = -9.81f;

    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMAsk;
    public float jumpHeight = 3f;

    Vector3 velocity;
    bool isGrounded;

  
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundCheck.position,groundDistance,groundMAsk);

        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x= Input.GetAxis("Horizontal");
        float z= Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;
      
        controller.Move(move  * speed  * Time.deltaTime);


        if(Input.GetButtonDown("Jump") && isGrounded)
        {

           velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);

        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
        
    }
 
Üst