用C#代码完成以下功能:1.完成第一人称操作及镜头控制脚本 2.完成角色持有物体的功能 3.完成物体被扔出的功能 4.完成物体与物体碰撞消失的功能
时间: 2024-02-23 19:57:56 浏览: 116
C# 基本功能
以下是用C#代码实现以上功能的示例:
1.完成第一人称操作及镜头控制脚本
```csharp
using UnityEngine;
public class FirstPersonController : MonoBehaviour
{
public float speed = 5f;
public float lookSensitivity = 3f;
private CharacterController controller;
private Camera cam;
private float xRotation = 0f;
void Start()
{
controller = GetComponent<CharacterController>();
cam = GetComponentInChildren<Camera>();
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
float mouseX = Input.GetAxis("Mouse X") * lookSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * lookSensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
transform.Rotate(Vector3.up * mouseX);
}
}
```
2.完成角色持有物体的功能
```csharp
using UnityEngine;
public class PickupObject : MonoBehaviour
{
public float pickupRange = 5f;
private GameObject heldObject;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (heldObject == null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, pickupRange))
{
heldObject = hit.collider.gameObject;
heldObject.transform.parent = transform;
heldObject.transform.localPosition = Vector3.zero;
heldObject.GetComponent<Rigidbody>().isKinematic = true;
}
}
else
{
heldObject.transform.parent = null;
heldObject.GetComponent<Rigidbody>().isKinematic = false;
heldObject = null;
}
}
}
}
```
3.完成物体被扔出的功能
```csharp
using UnityEngine;
public class ThrowObject : MonoBehaviour
{
public float throwForce = 10f;
private GameObject heldObject;
void Update()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (heldObject != null)
{
heldObject.transform.parent = null;
heldObject.GetComponent<Rigidbody>().isKinematic = false;
heldObject.GetComponent<Rigidbody>().AddForce(transform.forward * throwForce, ForceMode.Impulse);
heldObject = null;
}
}
}
}
```
4.完成物体与物体碰撞消失的功能
```csharp
using UnityEngine;
public class DestroyOnCollision : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
}
}
```
阅读全文