V
V
Vyacheslav Marvin2020-04-26 20:01:43
C++ / C#
Vyacheslav Marvin, 2020-04-26 20:01:43

Player movement diagonally, how does it work?

Hello.

There is such a code. Where is the movement forward, backward, left, right.

But there was a desire for him to move diagonally, relative to his Z vector. By pressing the W / A, W / D, S / A, S / D buttons.

Here is a piece of code:

private float X, Y, Z;
public int speed;
public int rotSpeed;

public float sensitivity = 3;
private Rigidbody rb;

private Vector3 movement = Vector3.zero;

public Player player;
private int speedX = 5;

private void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    //Поворот игрока
    X += Input.GetAxis("Mouse X") * rotSpeed * Time.deltaTime;
    Y += Input.GetAxis("Mouse Y") * rotSpeed * Time.deltaTime;

    transform.rotation = Quaternion.Euler(Y, X, Z);

    //Движение игрока
    float z = Input.GetAxis("Vertical");

    if (z != 0)
    {
        movement.z = z;
    }
    else
        movement = Vector3.zero;

    if (movement != Vector3.zero)

    rb.AddForce(movement * speed);

    if (Input.GetKey(KeyCode.D))
    {
        player.transform.position += Vector3.right * speedX * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.A))
    {
        player.transform.position -= Vector3.right * speedX * Time.deltaTime;
    }

}


After looking at the implementation of other users on the Internet. I did not find an answer for my case. Or it didn't work properly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ALTech1, 2020-04-28
@ALTech1

If I understand you correctly, then here's a way for you, of course, a collective farm, but still. Create a dummy and place it at a distance from your character. You make the dummy a child. And in the code you use MoveTowards. Thus, the dummy will spin with the character and he will move towards it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question