简体   繁体   中英

Player object changes position while rotating

First of all: Sorry for my bad English, I'm Dutch.

I'm trying to create a player object that can walk forward and backwards (with the up and down keys), and rotate the player with the right and left keys. But when I press the left or right key, the position of the player changes, it looks like it rotates around a certain point. But it should rotate and stay on the same place, like I do when I turn around.

I have some other small programs, with the same 'move script' and the same inputmanager settings. There it works fine, so I have no idea why it doesn't work this time.

This is my move script, but this script works fine with other programs:

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

public class MoveScript : MonoBehaviour
{

    public float speed = 3f;
    public float rotate = 50f;
    private Rigidbody rb;
    // Update is called once per frame

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    void Update()
    {
        if (Input.GetButton("Up"))
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        if (Input.GetButton("Down"))
            transform.Translate(-Vector3.forward * speed * Time.deltaTime);
        if (Input.GetButton("Right"))
            transform.Rotate(Vector3.up, rotate * Time.deltaTime);
        if (Input.GetButton("Left"))
            transform.Rotate(-Vector3.up, rotate * Time.deltaTime);
        if (gameObject.GetComponent<Rigidbody>().velocity.y < 0.01)
        {
            if (Input.GetButtonDown("Jump"))
                rb.AddForce(0, 225, 0);
        }

    }

}

The InputManager settings (also the same as other programs where it works fine):

在此处输入图片说明

在此处输入图片说明

If someone wants a screenshot of something else of my program, you can always ask it of course. I have no idea what the problem could be, if it isn't in the script or the inputmanager.

Following the comments in the OP, the solution should be to use:

if (Input.GetButton("Right"))
    transform.localEulerAngles = transform.localEulerAngles + new Vector3(xRotation, 0, 0) * Time.deltaTime;
if (Input.GetButton("Left"))
    transform.localEulerAngles = transform.localEulerAngles - new Vector3(xRotation, 0, 0) * Time.deltaTime;

Where xRotation is a float with the amount you want to rotate per second when and while one of the rotation keys is down.

(PS: Don't have unity open right now, so + and - might be inverted, but should be something like that.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM