大家好,我是技术小白,自己写博客既可以当作笔记,又可以帮助他人,一举两得,何不美哉?
好了不废话了,直接上代码。
提醒一下和我一样的入门小白,复制下面代码粘贴到一个新的C#脚本里时,
类名需要改成 和 外面文件名相同,否则没效果。
直接把下面脚本拖到 想要用双指放大缩小的游戏物体上即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//放大缩小功能 f
public class Scale : MonoBehaviour {
Vector2 oldPos1;
Vector2 oldPos2;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
if (Input.touchCount == 2) {
if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved){
Vector2 temPos1 = Input.GetTouch(0).position;
Vector2 temPos2 = Input.GetTouch(1).position;
if (isEnLarge(oldPos1, oldPos2, temPos1, temPos2))
{
float oldScale = transform.localScale.x;
//放大的倍数 如果要修改 列如:oldScale * 1.025f 修改成 oldScale * 1.25f 根据自己需求修改
float newScale = oldScale * 1.025f;
transform.localScale = new Vector3(newScale, newScale, newScale);
}else {
float oldScale = transform.localScale.x;
//缩小的倍数 如果要修改 列如:oldScale / 1.025f 修改成 oldScale / 1.25f 根据自己需求修改
float newScale = oldScale / 1.025f;
transform.localScale = new Vector3(newScale, newScale, newScale);
}
oldPos1 = temPos1;
oldPos2 = temPos2;
}
}
}
bool isEnLarge(Vector2 oP1,Vector2 oP2,Vector2 nP1,Vector2 nP2) {
float length1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
float length2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
if (length1 < length2)
{
return true;
}
else {
return false;
}
}
}
2.旋转功能
提醒一下和我一样的入门小白,复制下面代码粘贴到一个新的C#脚本里时,
类名需要改成 和 外面文件名相同,否则没效果。
直接把下面脚本拖到 想要用手指旋转的游戏物体上即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour {
//上一个手指的位置
//Vector3 PrevlousPosition;
//手指的偏移值
//Vector3 Offset;
//速度
float xSpeed = 150f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//如果触摸了屏幕
if (Input.GetMouseButton(0)) {
//判断是几个手指触摸
if (Input.touchCount == 1) {
//第一个触摸到手指头 phase状态 Moved滑动
if (Input.GetTouch(0).phase == TouchPhase.Moved) {
//根据你旋转的 模型物体 是要围绕哪一个轴旋转 Vector3.up是围绕Y旋转
transform.Rotate(Vector3.up*Input.GetAxis("Mouse X") * xSpeed * Time.deltaTime);
}
}
}
}
}
补充一点(重要)
如果发现模型 点击没有效果
可能是模型 没有加碰撞体 Collider