Hi,
after quite some time of searching and trying out several examples (without success), I thought I give it a try and ask the community myself…
I imagine this to be a newbie problem for many of you, but I guess that’s what I still am at the moment…
My Problem:
(Unity 4.3)
I have a 2D underwater scene with a fish.
The fish in its idle behaviour should be randomly swimming around, float, continue swimming and so on…
When I click /tap somewhere under water the fish should now swim to that point in a certain speed.
When I DOUBLE click somewhere the fish should swim to that point just a bit faster.
Can you give me advice on how to simply let the fish move to the clicked position, or do you know a tutorial / example
regarding this issue?
Im learning C# right now, so a solution in C# would be important.
I already tried several examples including the one from unify but it somehow never worked as desired…
Do I need raycasting for this, and if so, how do I set it?
Does anybody have an idea?
Help me ObiWan you’re my only hope!
There is no difference between 2D and 3D with respect to moving to the mouse position. An Orthographic camera does simplify the code a bit (2D or 3D). Here is a bit of starter code. If you Google “Unity3d move towards mouse position,” you will find other solutions.
using UnityEngine;
using System.Collections;
public class GotoMouse : MonoBehaviour {
public float speed = 1.5f;
private Vector3 target;
void Start () {
target = transform.position;
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
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
Move to Touch / Click Position - The Game Contriver
Hi, we made a 2d/2.5d point and click and it is now available on the asset store at Unity Asset Store - The Best Assets for Game Making
It might help you with your game. We also take requests of code so let us know what you need and we might be able to add it to the asset store.
holwerda.inc@gmail.com
hwaus.com