Unity joystick Control Object Mobile C # script

Source: Internet
Author: User
Using System.Collections;
Using System.Collections.Generic;
Using Unityengine;
Using Unityengine.eventsystems;
public class Joyscript:monobehaviour {


float radius=0;
The game object to control
public Gameobject player;
The speed at which objects move
public float speed = 0.1f;
Current position of the middle rocker
Recttransform Recttransform;
The original position of the rocker
Vector3 Originalpos;
Use this for initialization
void Start () {
Radius = transform.parent.getcomponent<recttransform> (). Rect.width/2;
Recttransform = getcomponent<recttransform> ();
Originalpos = recttransform.position;
}
<summary>
In the process of dragging and dragging
</summary>
<param name= "Data" >Data.</param>
public void Onjoudrag (Baseeventdata data) {
Determine the distance between the current position and the original rocker
If the rocker is within its circle
if (Vector3.distance (input.mouseposition, Originalpos) <= radius) {
Recttransform.position = input.mouseposition;


} else {
Get the direction vector of the mouse to the original position
Vector3 dir = input.mouseposition-originalpos;
Recttransform.position = dir.normalized * radius + originalpos;
}
}
public void Onjoudragend (Baseeventdata data) {
Recttransform.position = Originalpos;
}
void Fixedupdate () {
if (recttransform.position!= originalpos) {
float x, y;
if (Vector3.distance (input.mouseposition, Originalpos) <= radius) {
x = (Input.mouseposition-originalpos). x;
y = (input.mouseposition-originalpos). Y;
} else {
x = (input.mouseposition-recttransform.position). x;
y = (input.mouseposition-recttransform.position). Y;
}
Vector3 dor = new Vector3 (x, 0, y);
Player. Getcomponent<charactercontroller> (). Simplemove (DOR * time.deltatime);
}
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.