Proper way to move Rigidbody GameObject

后端 未结 4 789
说谎
说谎 2020-11-27 23:20

I just started learning Unity. I tried to make a simple box move by using this script. The premise is, whenever someone presses \'w\' the box moves forward.

         


        
4条回答
  •  庸人自扰
    2020-11-27 23:35

    Try this:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class PlayerMover : MonoBehaviour {
    
        public float speed;
        private Rigidbody rb;
    
    
        void Start () {
            rb = GetComponent();
        }
    
        void Update () {
            bool w = Input.GetKey(KeyCode.W);
    
            if (w) {
                Vector3 move = new Vector3(0, 0, 1) * speed *Time.deltaTime;
                rb.MovePosition(move);
                Debug.Log("Moved using w key");
    
            }
    
        }
    }
    

    Use Input.GetKey(KeyCode.W) for getting input.
    EDIT NOTE: To move the object relative to its initial position use rb.MovePosition(transform.position+move) rather than rb.MovePosition(move)

提交回复
热议问题