继续昨天的内容,昨天已经完成了基本的画笔功能,今天的目标实现:橡皮擦和笔刷大小的功能
过程:
1、给 Sphere 添加 rigidbody;
2、之后修改 Rigidbody 的属性,如图;
3、把 Player 子类中的 Cube 拖出来,不作子类改名为 Player 然后删除原来父类的 Player,把新 Player 做成预制件,同样加上 Rigidbody;把 play脚本拖上去,别忘拖 PrintPrefab(如图);
4、有了这些我们就可以做碰撞检测了,打开 player 脚本,在 void Update 下新写一个方法:
void OnCollisionEnter(Collision collision){ print ("OnCollisionEnter");
}
这样碰撞检测如果就做到了,就可以看到 Unity 左下角输出
OnCollisionEnter;
5、之后设置按鼠标右键就删除碰撞物体,代码如下图:
现在橡皮擦功能就实现了;
6、 现在准备改变笔刷的大小:
改变笔刷的大小就是改变 transform 中的 Scale 的值,所以打开 Player 脚本,再 Update 中添加:transform.localScale += Input.GetAxis ("Mouse ScrollWheel");
7、 调试发现报错:
Assets/Player.cs(18,27): error CS0019: Operator `+=' cannot be applied to operands of type `UnityEngine.Vector3' and `float'
大致意思为前面是个 Vector3 的向量,而后面是一个 float 值,不能做运算,所以修改 float;
transform.localScale += Input.GetAxis ("Mouse ScrollWheel") * Vector3.one;
这样就修改为 Vector3 的向量了。
8、 测试后发现,只有 cube 能放大,sphere 不能放大,所以再写个脚本命名为 Brush,在 Update 中写: transform.localScale += Input.GetAxis ("Mouse ScrollWheel") * Vector3.one;
最后拖拽脚本到 Sphere 上,点击 apply,这样预制件中就这个脚本;
9、 测试发现有问题,出来的 Sphere 同时根据鼠标滚轮变大变小;
10、 做最后的调试,问题出在调用问题,生成的 PrintPrefab 这个预制件,所以应该在这个上面做修改,在 player 脚本中 Update 加上:
PrintPrefab.transform.localScale += Input.GetAxis ("Mouse S crollWheel") * Vector3.one;
OK,最后测试成果。