应用场景:unity写一个FIFA21足球游戏里的球员c#脚本代码
using UnityEngine;
public class PlayerController : MonoBehaviour { public float speed = 10f; public float jumpForce = 500f; public float shootForce = 1000f; public GameObject ball; private Rigidbody rb; private bool isJumping = false;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
if (Input.GetKeyDown(KeyCode.Space) && !isJumping)
{
rb.AddForce(Vector3.up * jumpForce);
isJumping = true;
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
GameObject ballInstance = Instantiate(ball, transform.position + new Vector3(0, 1, 0), Quaternion.identity);
ballInstance.GetComponent<Rigidbody>().AddForce(transform.forward * shootForce);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isJumping = false;
}
}
原文地址: https://www.cveoy.top/t/topic/dj93 著作权归作者所有。请勿转载和采集!