把这个脚本挂在球上就完事了
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ray : MonoBehaviour
{
public float Speed;
public Vector3 direction;
public Vector3 OUT;
void Start()
{
}
void Update()
{
Debug.DrawLine(transform.position, transform.position + direction * 10, Color.red);
Ray ray = new Ray(transform.position, direction);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.tag == "wall")
{
float normalAngle = (hit.transform.eulerAngles.z + 180) * Mathf.Deg2Rad;
Vector3 nor = new Vector3(Mathf.Cos(normalAngle), Mathf.Sin(normalAngle), 0);
if (Vector3.Angle(direction,nor)<90)
{
nor = -nor;
}
Debug.DrawLine(hit.point, nor * 100 + hit.point);
OUT = Vector3.Reflect(direction, nor);
Debug.DrawLine(hit.point, hit.point + OUT,Color.green);
}
}
}
private void FixedUpdate()
{
this.transform.Translate(direction * Speed * Time.fixedDeltaTime, Space.World);
}
private void OnCollisionEnter(Collision collision)
{
direction = OUT;
}
}
|