unity---小球击打围墙
小球打方块
介绍#
- 自动生成围墙
- 射线瞄准器,并且发射小球
- 角色控制移动(角色控制器CharacterController)
- 摄像机跟随
制作步骤#
1. 构建基本场景#
2. 控制角色移动(CharacterController)#
3. 生成Walls#
4. 射线瞄准器#
效果#
获取一些必要的属性#
发出射线#
Update中实时检测射线碰撞的位置#
摄像头跟随#
源码一:物体移动#
注意脚本名和源码类名一致
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTarget : MonoBehaviour
{
CharacterController cc;
float speed =0;
private void Start() {
cc=this.gameObject.GetComponent<CharacterController>();
speed =10f*Time.deltaTime;
}
void Update()
{
if(Input.GetKey(KeyCode.W))cc.Move(transform.forward*speed);
if(Input.GetKey(KeyCode.S))cc.Move(-1f*transform.forward*speed);
if(Input.GetKey(KeyCode.A))cc.Move(-1f*transform.right*speed);
if(Input.GetKey(KeyCode.D))cc.Move(transform.right*speed);
// if(Input.GetKey(KeyCode.W))cc.Move(Vector3.forward*speed);
// if(Input.GetKey(KeyCode.S))cc.Move(Vector3.back*speed);
// if(Input.GetKey(KeyCode.A))cc.Move(Vector3.left*speed);
// if(Input.GetKey(KeyCode.D))cc.Move(Vector3.right*speed);
}
}
源码二:核心代码#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
public Transform tf;//主角
public Material material;//射线颜色
RaycastHit hit;//碰撞的位置
private void Start() {
//构建walls
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
obj.AddComponent<Rigidbody>();
obj.transform.position=new Vector3(0,2f*i,1f*j);
}
}
}
void OnPostRender(){
//画线
material.SetPass(0);
GL.Begin(GL.LINES);
// GL.Color(Color.green);
GL.Vertex(hit.point);
GL.Vertex(tf.position);
GL.End();
}
private void Update() {
//检测射线碰撞,发出小球
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,out hit)&&Input.GetMouseButtonDown(0)){
GameObject addobj =GameObject.CreatePrimitive(PrimitiveType.Sphere);
addobj.AddComponent<Rigidbody>();
addobj.transform.position=tf.position+Vector3.up*1f;
addobj.GetComponent<Rigidbody>().AddForce(100f*(hit.point-tf.transform.position));
Destroy(addobj,3);
}
}
private void LateUpdate() {
//摄像机跟随
this.transform.position = tf.position-tf.forward*4f+tf.up*2f;
this.transform.LookAt(tf.transform);
}
}
分类:
Unity学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了