Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C# Script for Moving an Object when screen is held

Discussion in 'Scripting' started by Jana1108, Nov 29, 2015.

  1. Jana1108

    Jana1108

    Joined:
    Jun 27, 2015
    Posts:
    215
    Hi, in my game I want to make it so that player object's y position will move -1 when the user touches and holds their finger on the screen (the app is for android). So far it just moves by -1 each time the screen it tapped but not held. Can someone help me write a script for this in C# please?
    Here is my current code -

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class PlayerMovement : MonoBehaviour {
    5.  
    6.     public GameObject Player;
    7.  
    8.     // Update is called once per frame
    9.     void Update () {
    10.         if(Input.GetMouseButtonDown(0))
    11.         transform.position = new Vector3(transform.position.x, transform.position.y - 1, transform.position.z);
    12.  
    13.     }
    14. }
     
    Last edited: Nov 30, 2015
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
  3. Jana1108

    Jana1108

    Joined:
    Jun 27, 2015
    Posts:
    215
  4. DMSolace

    DMSolace

    Joined:
    Nov 30, 2015
    Posts:
    9
  5. Jana1108

    Jana1108

    Joined:
    Jun 27, 2015
    Posts:
    215
  6. DMSolace

    DMSolace

    Joined:
    Nov 30, 2015
    Posts:
    9
    This would be what you're after.

    Code (CSharp):
    1.     public float speed = 5f;
    2.     private Vector3 playerPosition;
    3.     private bool isMoving;
    4.    
    5.     void Update () {
    6.    
    7.         playerPosition = transform.position;
    8.         if(Input.GetMouseButtonDown(0))
    9.         {
    10.             isMoving = true;
    11.         }
    12.         else if(Input.GetMouseButtonUp (0))
    13.         {
    14.             isMoving = false;
    15.         }
    16.    
    17.         if(isMoving)
    18.         {
    19.             playerPosition.y += -1 * speed * Time.deltaTime;
    20.             transform.position = playerPosition;
    21.         }
    22.     }
     
  7. Jana1108

    Jana1108

    Joined:
    Jun 27, 2015
    Posts:
    215
    This is perfect! Thank you so much I really appreciate this :D