0
\$\begingroup\$

I have 2 spheres and a cube on screen.

I'm experimenting to make a 'left/right movement script' for the cube so that when I touch the left sphere, the cube moves left-wards and when I touch the right sphere, the cube moves right-wards.

I have 2 scripts. I have attached SphereLeft.cs to left sphere and SphereRight.cs to right sphere.

Any pointers on how to achieve this ?

enter image description here

\$\endgroup\$
1
\$\begingroup\$

Here we are just one script, assign it to the cube TargetSlideControl.cs

using UnityEngine;
using System.Collections;

public class TargetSlideControl : MonoBehaviour {

public int SPEED = 1;
public Transform leftTrigger;
public Transform rightTrigger;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    // If Mobile
    if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer){
         if(Input.touchCount > 0) {
           checkTouch(Input.GetTouch(0).position);
         }
     }else if(Application.platform == RuntimePlatform.WindowsEditor){ // Else if Desktop
         if(Input.GetMouseButton(0)) {
           checkTouch(Input.mousePosition);
         }
     }
}

private void checkTouch( Vector2 pos ) {
    Ray ray = Camera.main.ScreenPointToRay( pos );
    RaycastHit hit;
    if(Physics.Raycast(ray, out hit)){
        if(hit.collider.transform  == leftTrigger) {
            SlideLeft();
        } else if(hit.collider.transform  == rightTrigger){
            SlideRight();
        }
    }
 }

// Call Translate on this transform passing SPEED * Direction * deltaTime

public void SlideLeft() {       
    this.transform.Translate( SPEED * Vector3.left * Time.deltaTime, Space.World );
}

public void SlideRight() {
    this.transform.Translate( SPEED * Vector3.right * Time.deltaTime, Space.World );
}
}

Assign the spheres in the editor to the TargetSlideControl script:

enter image description here

ENJOY!

\$\endgroup\$
  • \$\begingroup\$ Is it working in your editor/windows Desktop/Android phone ? I did what you said but the spheres are not receiving the touches on touching. I tried on an android phone, windows desktop. Not working. \$\endgroup\$ – Gissipi_453 Apr 5 '15 at 14:10
  • \$\begingroup\$ Sure it works! Have you dragged the spheres in the editor to leftTrigger and rightTrigger in the script? \$\endgroup\$ – SharpEdge Apr 5 '15 at 14:12
  • \$\begingroup\$ Sorry i forgot to tell you that the spheres need a collider applied \$\endgroup\$ – SharpEdge Apr 5 '15 at 14:31
  • \$\begingroup\$ No problem. I applied collider and ticked on 'Is Trigger' the cube. Accepted answer. \$\endgroup\$ – Gissipi_453 Apr 5 '15 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.