- Home /
Question by
stephenshettler02 · May 16, 2018 at 05:53 AM ·
movementgameobjectmovement scriptmove an object
How to drag a game object with a mouse (along x axis)?
I want the user to be able to drag the spaceship across the phone screen (x axis) but not up or down (y axis) by dragging it left or right with their mouse. I also want to implement borders so the spaceship stops at the edge of the phone screen. How would I do this? I am using a C# script.
Thanks so much!!
Comment
transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, 0f,Input.mousePosition.z+10f));
this code to move object on left and right and set colliders to the camera bound
Answer by Uchiha312 · Aug 23, 2020 at 02:58 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Drag : MonoBehaviour
{
Vector3 first, second;
public float speed = 15;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
first = Camera.main.ScreenToViewportPoint(new Vector3(Input.mousePosition.x, 0, 0));
}
if (Input.GetMouseButton(0))
{
second = Camera.main.ScreenToViewportPoint(new Vector3(Input.mousePosition.x, 0, 0));
Vector3 diff = second - first;
transform.position += diff * speed;
first = second;
}
}
}
Your answer
Follow this Question
Related Questions
move enemy to old position of player 2 Answers