当前位置:网站首页>Realize the reset function of steering wheel UI with touch rotation and finger departure in unity
Realize the reset function of steering wheel UI with touch rotation and finger departure in unity
2022-07-28 17:05:00 【More than a curtain a dream】
The need is Steering wheel simulation UI, Rotation is to press and hold the steering wheel to rotate , The limit is only one and a half turns left and one and a half turns right , The steering wheel resets automatically when you let go .
First on the final rendering :

Let's talk about the specific implementation process . The first is to realize that the steering wheel rotates with the position of the mouse . The idea is to record the pressed point followed by the steering wheel at each frame after pressing the mouse 0 The center is the coordinate origin y The angle of the coordinate axis , As shown in the figure below, yellow ∠1 Shown ( The black dot is the position of one frame on the mouse , The red dot is the current frame position of the mouse )

Then use the current frame angle blue ∠2 Keep up with the frame angle yellow ∠1 Compare , Get a difference black ∠3. use transform.Rotate() Method rotate the difference to make the steering wheel rotate with the mouse .
The second requirement is to make the steering wheel rotate left and right no more than one and a half turns , That is to say 450°. The implementation of this requirement is to customize a float Field , Used to record the total rotation angle , use ∠1 and ∠2 The difference between positive and negative determines whether the current mouse is turning clockwise or counterclockwise , Determine whether the current angle is plus or minus the total angle .
Let's talk about it here unity The two methods that come with it :
Vector3.Angle(Vector3 from,Vector3 to) This method is used to calculate the relative coordinates of two positions (0,0,0) The angle between , The value returned is always [0,180] Between .
Vector3.Cross(Vector3 lhs,Vector3 rhs) This method is used to calculate the cross product of two positions , Return to one Vector3 v3, The calculation is carried out clockwise and counterclockwise in the plane , Ignore y Axis , be v3.z>0,rhs stay lhs In a clockwise direction ;v3.z = 0,rhs Follow lhs parallel ;v3.z<0,rhs stay lhs In the counter clockwise direction of .
( A more detailed introduction to dot and cross products : http://blog.csdn.net/liqiangeastsun/article/details/50331933)
Reset is simple , It is to monitor that when the mouse releases the steering wheel, the total rotation angle of the previous record is increased or decreased to 0, Just make the steering wheel angle equal to this total angle .
Here's the code :
public Canvas CanvasRoot;// canvas
private RectTransform m_RectTransform;// coordinate
private bool m_IsFirst = true; // Used to record the position of the mouse when the mouse is pressed in the first frame , Easy to calculate
private Vector3 m_CurrentPos; // Record the position of the mouse in the current frame
private bool m_IsClockwise; // Is it clockwise
private float m_RoundValue = 0; // Record the total rotation angle Use this value to control one and a half circles
private bool m_IsTuringSteeringWheel; // Are you turning the steering wheel Reset with this judgment
void Start()
{
CanvasRoot = GameObject.Find("Canvas").GetComponent<Canvas>();
m_RectTransform = CanvasRoot.transform as RectTransform;
}
void Update()
{
if (Input.GetMouseButton(0) && EventSystem.current.currentSelectedGameObject == gameObject) // When the mouse clicks on the steering wheel
{
m_IsTuringSteeringWheel = true;
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_RectTransform, Input.mousePosition, CanvasRoot.worldCamera, out pos)) // Get the mouse click position
{
pos.x = pos.x + (Screen.width / 2) - GetComponent<RectTransform>().position.x;
pos.y = pos.y + (Screen.height / 2) - GetComponent<RectTransform>().position.y;
Vector3 pos3 = new Vector3(pos.x, pos.y, 0); // Calculate the coordinate position of the mouse with the center of the steering wheel as the coordinate origin
if (m_IsFirst)
{
m_CurrentPos = pos3;
m_IsFirst = false;
}
Vector3 currentPos = Vector3.Cross(pos3, m_CurrentPos); // Calculate the finger position of the current frame and the previous frame Used to judge the direction of rotation
if (currentPos.z > 0)
{
m_IsClockwise = true;
}
else if (currentPos.z < 0)
{
m_IsClockwise = false;
}
if(m_CurrentPos != pos3) // Turn the steering wheel with your fingers within the range
{
if(m_IsClockwise)
{
if (m_RoundValue <= 540)
{
m_RoundValue += Vector3.Angle(m_CurrentPos, pos3);
transform.Rotate(new Vector3(0, 0, -Vector3.Angle(m_CurrentPos, pos3)));
}
}
else
{
if (m_RoundValue >= -540)
{
m_RoundValue -= Vector3.Angle(m_CurrentPos, pos3);
transform.Rotate(new Vector3(0, 0, Vector3.Angle(m_CurrentPos, pos3)));
}
}
}
m_CurrentPos = pos3;
}
}
if (Input.GetMouseButtonUp(0))
{
m_IsFirst = true;
m_IsTuringSteeringWheel = false;
}
if (!m_IsTuringSteeringWheel && m_RoundValue != 0) // Reset
{
if (m_RoundValue >= 0)
{
m_RoundValue -= 8f; // Reset speed
if (m_RoundValue < 0)
m_RoundValue = 0;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, -m_RoundValue));
}
else
{
m_RoundValue += 8f;
if (m_RoundValue > 0)
m_RoundValue = 0;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, -m_RoundValue));
}
}
}
}边栏推荐
- [deep learning]: day 1 of pytorch introduction to project practice: data operation and automatic derivation
- go语言慢速入门——流程控制语句
- PostgreSQL weekly news - July 20, 2022
- Android Development - set cache
- 【深度学习】:《PyTorch入门到项目实战》第八天:权重衰退(含源码)
- Programmers from entry to roast!!!!
- [deep learning]: day 5 of pytorch introduction to project practice: realize softmax regression from 0 to 1 (including source code)
- [deep learning]: model evaluation and selection on the seventh day of pytorch introduction to project practice (Part 1): under fitting and over fitting (including source code)
- 浏览器解码过程分析
- Given positive integers n and m, both between 1 and 10 ^ 9, n < = m, find out how many numbers have even digits between them (including N and m)
猜你喜欢

Applet: get element node information

Re11: read EPM legal judgment prediction via event extraction with constraints
![[deep learning]: day 8 of pytorch introduction to project practice: weight decline (including source code)](/img/19/18d6e94a1e0fa4a75b66cf8cd99595.png)
[deep learning]: day 8 of pytorch introduction to project practice: weight decline (including source code)

MySQL 5.7 and sqlyogv12 installation and use cracking and common commands

Interesting kotlin 0x06:list minus list

Brother Ali teaches you how to correctly understand the problem of standard IO buffer

Re12: read these3 semantic self segmentation for abstract summary of long legal documents in low

Re13: read the paper gender and racial stereotype detection in legal opinion word embeddings

结构化设计的概要与原理--模块化

MySQL安装教程
随机推荐
【深度学习】:《PyTorch入门到项目实战》第五天:从0到1实现Softmax回归(含源码)
Text filtering skills
Egg (19): use egg redis performance optimization to cache data and improve response efficiency
SUSE CEPH rapid deployment – storage6
A total of 13billion flash and 400million MCU were shipped! In depth analysis of the three product lines of Zhaoyi innovation
[deep learning]: day 6 of pytorch introduction to project practice: multi-layer perceptron (including code)
累计出货130亿颗Flash,4亿颗MCU!深度解析兆易创新的三大产品线
2020Q2全球平板市场出货大涨26.1%:华为排名第三,联想增幅最大!
RE14: reading paper illsi interpretable low resource legal decision making
Interesting kotlin 0x09:extensions are resolved statically
Interesting kotlin 0x0a:fun with composition
Signal and slot mechanism of QT learning
2019年全球移动通信基站市场:爱立信、华为、诺基亚分列前三
Rsync service deployment and parameter details
Do you really understand CMS garbage collector?
做题笔记5(有序数组的平方)
NoSQL introduction practice notes I
Technology sharing | how to recover the erroneously deleted table and the data in the table?
MySQL CDC if the binlog log file is incomplete, can you read all the data in the full volume stage
Reduce cycle complexity