Мы с приятелем недавно объединились, чтобы создать космическую стрелялку с видом сверху, вроде астероидов. Мы просмотрели много руководств, и нам удалось поработать с translate.Transform()
и заставить наш объект двигаться.
Теперь мы хотим применить силу к нашему кораблю, используя RigidBody2D
:
Вот скриншот нашего окна Unity:
Как видно на скриншоте выше, мы создали префаб корабля игрока со спрайтом космического корабля, коллайдером круга, твердым телом 2D и скриптом PlayerThrust.
In Thrust.cs
:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Thrust : MonoBehaviour
{
// Thrust script components
public Rigidbody2D rigidBody; // GameObject's Rigidbody2D component
public float thrustAmount; // amount of thrust applied to be defined in unity
private float thrustInput; // float variable to keep track of user input of the 'up' arrow key/'up' axis tilt on joystick
// Start is called before the first frame update
void Start() {}
// Update is called once per frame
void Update()
{
// handle input
thrustInput = Input.GetAxis("Vertical"); // float ranging from -1.0 to +1.0
// Debug
Debug.Log(Vector2.up * thrustInput * thrustAmount);
}
// Fixed Update is called every fixed framerate frame
// use for physics
void FixedUpdate() {
// only accelerate forward
if (thrustInput > 0)
{
// Apply thrust in direction ship is facing
rigidBody.AddRelativeForce(transform.up * thrustInput * thrustAmount);
}
}
}
Почему корабль не двигается?
Debug.Log(Vector2.up * thrustInput * thrustAmount);
выводит число, которое имеет смысл: оно увеличивается до величины тяги при нажатии кнопки ↑ и возвращается к 0,0 при отпускании кнопки.