简体   繁体   English

如何使用 Unity 3D 中的 A 和 D 键使播放器 object 旋转?

[英]How can I make a Player object rotate using the A and D keys in Unity 3D?

I need some help as someone brand new to Unity and C# coding.作为 Unity 和 C# 编码的新手,我需要一些帮助。 The problem that I am currently facing is that I need my player model to only be able to rotate left and right instead of move on all three axis like many tutorials I have found online.我目前面临的问题是我需要我的播放器 model 只能左右旋转,而不是像我在网上找到的许多教程一样在所有三个轴上移动。 The code I have currently got is:我目前得到的代码是:

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

public class PlayerRotation : MonoBehaviour
{
    private void Update()
    {
        Rigidbody rb = GetComponent<Rigidbody>();
        if (Input.GetKey(KeyCode.A))
        rb.AddForce(Vector3.left);
        if (Input.GetKey(KeyCode.D))
        rb.AddForce(Vector3.right);
    }

}

But the issue with this is that instead of rotating, the player physically moves left and right.但问题在于,玩家不是旋转,而是身体左右移动。 Is anyone able to help with this?有人可以帮忙吗? (preferably with some code) (最好有一些代码)

Instead of rigidboy, you can directly use the object's transform.您可以直接使用对象的变换来代替rigidboy。 So you won't have any problems.所以你不会有任何问题。

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

public class PlayerRotation : MonoBehaviour
{
    public float turnSpeed;
    private void Update()
    {
        if (Input.GetKey(KeyCode.A))
           transform.Rotate(Vector3.left * turnSpeed);
        if (Input.GetKey(KeyCode.D))
           transform.Rotate(Vector3.right * turnSpeed);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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