P
P
parusa2021-12-19 13:19:28
C++ / C#
parusa, 2021-12-19 13:19:28

How to make a third person game?

I am making a game similar to the balance game, there is a ball that rolls around the world.
Here is the code with which he does this:

private Rigidbody rb;
public int speed = 1; // скорость передвижения
    void Start()
    {
        // Получить доступ к компоненту Rigidbody
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        // Нажатие стрелочки влево или вправо
        float moveHorizontal = Input.GetAxis("Horizontal");

        // Нажатие стрелочки вперёд или назад
        float moveVertical = Input.GetAxis("Vertical");

        // Перемещение шара
        Vector3 movement = new Vector3(moveHorizontal * speed, 0.0f, moveVertical * speed);
        rb.AddForce(moveHorizontal * speed, 0.0f, moveVertical * speed);
    }

Next, I installed cinemamachine and set it up
. What is the problem, if you turn the camera in the game when you press the forward button, it goes back due to the fact that the camera angle is changed, this needs to be fixed

. but as it turned out, the addForce method works on global coordinates
. If you use addRelativeForce, then it works, but there is a problem due to the fact that the ball also rotates when it moves. AddRelativeForce does not work correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
KraGen.Developer, 2021-12-19
@KraGenDeveloper

in short: You have a "Player" and an empty Object. On an empty object, you throw a script that takes the coordinates of movement from the "Player" and and moves to them. Ie here is the script in the inspector add the player. Throw it on an empty object that the camera is watching

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

public class TargetCamera : MonoBehaviour
{
    public GameObject Player;
    Vector3 pos;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        pos.x = Player.transform.position.x;
        pos.y = Player.transform.position.y;
        pos.z = Player.transform.position.z;

        transform.position = new Vector3(pos.x, pos.y,pos.z);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question