先制作一个Arm空物体,在Arm下创建子物体,body(一个square)和一个top空物体(将位置拖动到手臂的最顶端)
然后再创建一个Brush空物体,将位置拖动到,再创建一个body的square
将左上方设置为pivot,再将body拖到Brush下面,让Brush的中心点不变(保持在末端)
建立一个Brush脚本,用于将牙刷的右端始终和手臂末端连接在一起
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Brush : MonoBehaviour
{
public Transform AnchorPoint;
private void Update()
{
transform.position = AnchorPoint.position;
}
}
再建立一个空物体MouseManager,将一个新建的脚本MouseManager拖拽上去(记得将arm里的body添加collider2d,并将其tag设置为Arm)(要注意调整collider)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class MouseManager : MonoBehaviour
{
public static Action<Vector3> MouseMove;
public GameObject Arm;
//public Arm armScript;
public Transform MyPosition;
public float maxAngle;
private bool bInRange;
private bool bClick;
private Vector3 currentPosition;
private float currentAngle;//鼠标与y轴的角度
private void Update()
{
bInRange = false;
if (Input.GetMouseButtonDown(0))
{
bClick = true;
}
if (Input.GetMouseButtonUp(0))
{
bClick = false;
}
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var info = Physics2D.Raycast(pos, pos - transform.position);
if(info.collider != null)
{
//Debug.Log("collide sth");
if (info.collider.gameObject.CompareTag("Arm"))
{
Debug.Log("arm!!!!");
bInRange = true;
}
}
RotateArm();
}
public void RotateArm()
{
if (bInRange&&bClick)
{
//获得位置
currentPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
currentPosition.z = 0;//记得一定要设置,不然的话会出问题
Debug.Log(currentPosition);
//获得角度,超过最大角度就不移动
var pos = Vector3.SignedAngle(Vector3.up, currentPosition - Arm.transform.position, Vector3.forward);//这里要注意signedangle的用法
// currentAngle = pos;
currentAngle = (pos <= maxAngle && pos >= 0) ? pos : 0 ; //: pos;
//调整手臂旋转角度
Arm.transform.eulerAngles = new Vector3(0, 0, currentAngle);
}
else
{
Arm.transform.eulerAngles = new Vector3(0, 0, 0);
}
//重置canrotate
}
}
最后建立一个ShowWindow的square,为他添加rect transform,作为白色背景,调整到合适大小和想要的位置
ctrl+d 一个Brush的body,重命名为littlebrush,拖拽为其子物体 ,
创建ShowWindow脚本,拖拽到ShowWindow上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShowWindow : MonoBehaviour
{
public Transform Brush;
private Transform littleBrush;
public float ratioWidth,ratioHeight;
private void Awake()
{
// ratioWidth = GetComponent<RectTransform>().rect.width/Screen.width;
//ratioHeight = GetComponent<RectTransform>().rect.height/Screen.height;
littleBrush = transform.GetChild(0);
}
private void Update()
{
littleBrush.localPosition = new Vector3(Brush.position.x * ratioWidth,Brush.position.y * ratioHeight, Brush.position.z) ;
}
}
大功告成!