GDPU unity游戏开发 角色控制器与射线检测

在你的生活中,你一直扮演着你的角色,别被谁控制了。

小试

1. 创建一个角色控制器,通过键盘控制角色控制器的移动,角色控制器与家具发生碰撞后,通过Debug语句打印出被碰撞物体的信息(搜索OnControllerColliderHit的使用方法)。

2. 通过屏幕射线进行碰撞检测,使得鼠标点击某个家具后,通过Debug语句打印该物体的信息。

先搭建好场景

 

然后以玩具小车做角色控制器

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private CharacterController controller;
    float speed = 5.0f;

    void Start()
    {
        // 获取角色控制器组件
        controller = GetComponent<CharacterController>();
    }
    void Update()
    {
        // 获取键盘输入,相对全局坐标移动
        float hInput = Input.GetAxis("Horizontal");
        float vInput = Input.GetAxis("Vertical");

        // 计算移动方向
        Vector3 moveDirection = new Vector3(hInput, 0, vInput);
        moveDirection = transform.TransformDirection(moveDirection);//转为全局坐标

        // 使用角色控制器进行移动
        controller.Move(moveDirection * speed * Time.deltaTime);
    }
//    // 获取角色的 Transform 组件
//Transform characterTransform = characterController.transform;

 将全局坐标系中的输入值转换为角色本地坐标系中的输入值
//Vector3 moveInput = new Vector3(hInput, 0, vInput);
//moveInput = characterTransform.InverseTransformDirection(moveInput);

 在角色的本地坐标系中应用输入值
//characterController.Move(moveInput * Time.deltaTime * moveSpeed);
    // 当角色控制器与其他碰撞体发生碰撞时调用
    void OnControllerColliderHit(ControllerColliderHit hit)
    {
        // 打印被碰撞物体的信息
        Debug.Log("Collision with: " + hit.collider.gameObject.name);
    }
}

 

把射线检测挂载在相机上

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class sctoRay : MonoBehaviour
{
    void Update()
    {
        // 检测鼠标左键是否被点击
        if (Input.GetMouseButtonDown(0))
        {
            // 发射一条射线从鼠标点击的位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            // 检测射线是否击中物体
            if (Physics.Raycast(ray, out hit))
            {
                // 获取击中物体的信息并打印
                GameObject hitObject = hit.collider.gameObject;
                //Debug.DrawLine(ray.origin, hit.point, Color.red,5);
                Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red, 5);
                Debug.Log("Clicked on: " + hitObject.name);
                Debug.Log("Position: " + hitObject.transform.position);
                Debug.Log("Rotation: " + hitObject.transform.rotation.eulerAngles);
                Debug.Log("Scale: " + hitObject.transform.localScale);
                // 可以打印更多信息,如碰撞体、脚本组件等

                
            }
        }
    }
}

实验心得 

哪家的天才少年亦为情所束缚,所以归途在哪。

 

 

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值