gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
tôi muốn code di chuyển có cả giảm tốc và tăng tốc trong unity
- User
tôi muốn code di chuyển có cả giảm tốc và tăng tốc trong unity
- Assistant
Đây là một ví dụ đơn giản về di chuyển với cả giảm tốc và tăng tốc trong Unity:
using UnityEngine; public class ObjectMovement : MonoBehaviour { public float acceleration = 5f; // Tốc độ tăng tốc public float deceleration = 2f; // Tốc độ giảm tốc public float maxSpeed = 10f; // Tốc độ tối đa private Rigidbody rb; private float currentSpeed = 0f; private void Start() { rb = GetComponent<Rigidbody>(); } private void Update() { // Input từ người dùng float moveInput = Input.GetAxis("Vertical"); // Tăng tốc if (moveInput > 0 && currentSpeed < maxSpeed) { currentSpeed += acceleration * Time.deltaTime; } // Giảm tốc else if (moveInput < 0 && currentSpeed > 0) { currentSpeed -= deceleration * Time.deltaTime; } // Ngừng di chuyển else if (moveInput == 0 && currentSpeed > 0) { currentSpeed -= deceleration * Time.deltaTime; } // Đặt vận tốc của đối tượng rb.velocity = transform.forward * currentSpeed; } }Đặt script trên vào một đối tượng trong Unity để thực hiện di chuyển. Bạn cần phải gắn Rigidbody component vào đối tượng để nó có thể di chuyển và tương tác với physics engine của Unity.