Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

c# - Unity - camera movement on pivot child make unexpected character bounce

this is my first script, it may be a mess. Sorry.

My goal is to make the character move x-z using w-a-s-d axis, and rotate the camera on Y (clamped) using mouse X axis.

I managed something, but now if camera and movement goes the same way while moving, capsule starts to bounce on Y position.

I know you can lock Y position to "fix it", i just want to understand why is happening.

The hierarchy is:

  • Capsule
    • PivotCamScript
      • Main Camera

The code is in two scripts:

Capusle script:

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

public class CarroRapido : MonoBehaviour{

    private float doblar;
    private float moverse;
    public Rigidbody rb;
    private float hAxis;
    private float vAxis;
    public bool rapido;

    // Start is called before the first frame update
    void Start()
    {
        rapido = true;
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        hAxis = Input.GetAxis("Horizontal");
        vAxis = Input.GetAxis("Vertical");

        moverse += vAxis;           
        moverse = Mathf.Clamp (moverse, -5, 7);
        rb.AddRelativeForce(Vector3.forward * moverse);

        doblar += hAxis;
        transform.rotation = Quaternion.Euler(0, doblar, 0);

        if (vAxis == 0)
        { 
            moverse -= moverse * 0.75f;
        }
    }
}

PivotCamScript:

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

public class PivotCamScript : MonoBehaviour
{

    private bool rapido;
    private float CamRot;

    // Start is called before the first frame update
    void Start()
    {
        rapido = false;
        Cursor.lockState = CursorLockMode.Locked;
        rapido = GameObject.Find("Capsule").GetComponent<CarroRapido>().rapido;

    }

    // Update is called once per frame
    void Update()
    {
        CamRot += Input.GetAxis("Mouse X");
        CamRot = Mathf.Clamp(CamRot, - 15, 15);
        Debug.Log("CamRot = " +CamRot);

        if (rapido == true)
        {
            transform.localRotation = Quaternion.Euler(0, CamRot, 0);
        }

    }
}

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...