-
今天学了C#常见API,并进行测试:
1.CharacterController组件中,simpleMove与Move方法,isGrounded方法,OnControllerColliderHit事件监听器。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerCC : MonoBehaviour
{
private CharacterController cc;
public float speed = 1;
// Start is called before the first frame update
void Start()
{
cc = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
cc.SimpleMove(new Vector3(h, 0, v) * speed);
//SimpleMove参数是速度,并且有重力,不用乘Time.deltaTime
//cc.Move(new Vector3(h, 0, v) * speed*Time.deltaTime);
//这个Move参数是移动距离,需要乘Time.deltaTime,无重力
//Debug.Log("isGrounded" + cc.isGrounded);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
//Debug.Log(hit.collider);
}
}
2.射线检测常用方法:Physical.Raycast()方法的重载用法,Mathf.Infinity是最大值,利用out RaycastHit hit来得到被射线检测到的信息。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = new Ray(transform.position+new Vector3 (transform.position.x,0,0), transform.forward);
//可能跟自身发生碰撞,所以要+一个position的x距离(大约)
//bool isCollider = Physics.Raycast(ray);
//Debug.Log(isCollider);
//Physics.Raycast(ray, 1);
//Physics.Raycast(ray,out RaycastHit hit);
//out RaycastHit HitInfo是存储碰撞信息用的
//Debug.Log(hit.collider);
//被碰撞的信息:hit.transform。hit.collider.gameObject不能Debug,因为hit.collider可能是空指针
//Debug.Log(hit.point);//碰撞到的点
bool isCollider = Physics.Raycast(ray,Mathf.Infinity,LayerMask.GetMask("Enemy1"));
//只对Enemy1有射线检测反应
Debug.Log(isCollider);
}
}
3.照相机Camera的ScreenPointToRay方法,利用它来得到鼠标瞄准位置的射线。Debug.DrawRay(),Debug.DrawLine()可以画射线。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraTest : MonoBehaviour
{
private Camera camera;
// Start is called before the first frame update
void Start()
{
camera = Camera.main;
}
// Update is called once per frame
void Update()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(ray.origin, ray.direction);
//Debug.DrawLine(ray.origin,ray.direction * 100);
bool isCollider = Physics.Raycast(ray,out RaycastHit hitInfo);
Debug.Log(isCollider+"\n"+hitInfo.collider);
//不能打印hitInfo.collider.gameObject,避免射线指向空时,出现空指针,空指针的GameObject会报错
}
}
-
确定了Unity假期互动作业的任务解决方案:先搭建一个主场景,人物到汽车旁边,点击某按键就可以切换到展示场景,2D展示汽车部件来进行介绍。