- Home /
Button click moves GameObject to specific position
Hi there,
I'm making a menu in 3D and need a hand with it.
I've got several working buttons/tabs that has a rectangle above the current tab. I want to animate the rectangle to move to the relevant position on a mouse click. For example, it's currently above 'Welcome' but when 'Help' is clicked, the rectangle moves to above the 'Help' button.
I'm fairly new to coding so I know I need to write a script that says something along the lines of 'find out current position and move to this specific position on mouse click' (possibly using Raycast) but not sure how to phrase in it .js. I would appreciate any help!
Here's the script I've tried but whenever the button is clicked it goes 0.4 on the z axis
pragma strict
var transform : Transform; var NavBar : GameObject; private var ray: Ray; private var hit : RaycastHit; function Start () {
}
function Update () {
if(Input.Get$$anonymous$$ouseButtonDown(0)){
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit)){
if(hit.transform.name == "IndustryBtn"){
NavBar.transform.Translate(0,0,0.4);
Answer by Jamora · Aug 08, 2013 at 03:40 PM
You are currently moving it to position (0,0,0.4). To move it to the position of the hit point, you will need
NavBar.transform.Translate(hit.position);
Thanks for the reply.
That seems to make more sense, however, do I need to add a var because I'm getting an error message saying "'position' is not a member of 'UnityEngine.RaycastHit'.
Answer by hollym16 · Aug 09, 2013 at 09:27 AM
Thanks to Jamora (and some research) I've worked it out! That last bit needs to be:
NavBar.transform.position = hit.point;
I just need to work out how to constrain it to one axis now, anyone have any ideas?
Answer by falconer · Oct 22, 2014 at 05:53 AM
This is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position. You can find the article by The Game Contriver on the same here
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Inspector scripting, adding lists, checkboxes and buttons [With Image] 0 Answers
How to do Menu and Submenu UI - Hide/Collapse 2 Answers
Main Menu button in pause menu 0 Answers
Back button on menu to go back to previous menu screen 0 Answers