创建小球写入c#代码
using UnityEngine;
public class BallController : MonoBehaviour
{
public float speed = 5f;
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
transform.Translate(movement * speed * Time.deltaTime);
}
}
现在小球可以移动了再给小球添加重力和碰撞效果
using UnityEngine;
public class BallController : MonoBehaviour
{
private Rigidbody rb;
public float speed = 5f;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.mass = 1f; // 设置小球质量
rb.drag = 0.5f; // 设置空气阻力
rb.angularDrag = 0.5f; // 设置角阻力
rb.useGravity = true; // 启用重力
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);
rb.AddForce(movement * speed);
}
}
这样小球会受到真实引擎的效果