- Home /
Moving an object back and forth with mouse click
So, I am a newbie when it come to scripting in unity, Using c# I am trying to make a "weapon" move forward, then back again when the "player" clicks the left mouse button. The weapon is a parent of the player so when the player rotates, the weapon does as well so its stays the same position relative to the player. Now what I want it to do is simply move forward then back to the same position. This is what I have so far:
using UnityEngine; using System.Collections;
public class WeaponControl : MonoBehaviour { GameObject Weapon; public float attackSpeed;
// Use this for initialization
void Start () {
Weapon = GameObject.Find ("Weapon");
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
Weapon.transform.position += transform.right * Time.deltaTime * attackSpeed;
} else if (Input.GetMouseButtonUp (0)) {
Weapon.transform.position -= transform.right * Time.deltaTime * attackSpeed;
}
}
Now what tends to happen is, if I click the left mouse button to fast it begins to move farther away from the player either behind the player or in front of. The transform.right and -transform.right I have to use I'm guessing because of how I scaled the weapon object and its starting position and orientation. How do I make this go forward and back to the original position no matter how fast the player clicks and so on.