繁体   English   中英

我是 c# 和 unity 的新手,我无法获得基于物理旋转的运动(c# unity)

[英]I'm new at c# and unity and I am having trouble with getting a movement based on rotation with physics(c# unity)

我无法获得基于物理旋转的运动(比如上坡、跳跃和撞墙),我可以用另一个代码环顾四周,但我无法让胶囊按照其指向的方向移动,并且当我这样做时,我不能跳,go 上坡道,我可以穿过墙壁。 有人可以帮忙吗?

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

public class pm : MonoBehaviour
{
CharacterController characterController;
public float movementSpeed;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public float speed = 9.0f;






    public Vector3 jump;
    public float jumpForce = 2.0f;

    public bool isGrounded;
    Rigidbody rb;

private Vector3 moveDirection = Vector3.zero;




// Use this for initialization
void Start()
{
    characterController = GetComponent<CharacterController>();
    rb = GetComponent<Rigidbody>();
    jump = new Vector3(0.0f, 2.0f, 0.0f);
}

void OnCollisionStay()
{
    isGrounded = true;
}

    //Update is called once per frame
    void FixedUpdate()
{
    var horizontal = Input.GetAxis("Horizontal");
    var vertical = Input.GetAxis("Vertical");


    Cursor.visible = false;
    if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey("w"))
    {
        transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed * 2.5f;
    }
    else if (Input.GetKey("w") && !Input.GetKey(KeyCode.LeftShift))
    {
        transform.position += transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
    }
    else if (Input.GetKey("s"))
    {
        transform.position -= transform.TransformDirection(Vector3.forward) * Time.deltaTime * movementSpeed;
    }

    if (Input.GetKey("a") && !Input.GetKey("d"))
    {
        transform.position += transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
    }
    else if (Input.GetKey("d") && !Input.GetKey("a"))
    {
        transform.position -= transform.TransformDirection(Vector3.left) * Time.deltaTime * movementSpeed;
    }
    moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
    moveDirection *= speed;
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {

        rb.AddForce(jump * jumpForce, ForceMode.Impulse);
        isGrounded = false;
    }
   
}
}

首先,您不应该使用 FixedUpdate() 来获取输入,因为它不会运行每一帧。 您有时会在游戏过程中跳过输入。 在 Update() 中使用它。

并用于跟随相机运动。 使用 = transform.LookAt(target.transform.position);

问题是您试图用 rb.AddForce() 覆盖 transform.position。 transform.position 正在将您的 (x,y,z) 设置为每帧的某个精确值,并且您正试图在您的 transform.position 将您的 y 值设置为 0 的同时向您的 y 值添加力。不要使用 transform.position+= 作为运动系统。 您可以使用已定义但从未用作 transform.Translate(moveDirection movementSpeed Time.deltaTime); 的 moveDirection

暂无
暂无

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

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