With the help of a script I found on here, I was able to move a butterfly sprite to a new random location. However, I need to first load the x and y values of the new location Vector3 into another Vector3.x and .y, otherwise it does not work. Logically I would think that I can use directly the randomly defined targetPosition Vector3. I would like to understand what is wrong in my logic.
I have the 2 scripts below. Script 1 works, but is not logical to me. Script 2 should work in my opinion but does not.
The way it works:
I have a butterfly sprite in my world
At Start, I select a random point on a sphere and make this my targetPosition
Then in Update, I check the current location of the butterfly and move it towards the targetPosition.
In script 1 this works but I first put the random target location into Vector3 targetPos and then assign targetPos.x to targetPosition.x and same for y.
In script 2 I put the random location directly into targetPoistion and looking at the debug.log, the x and y values are not zero.
Could someone please explain what is wrong in my logic of script 2 and explain how I should move my butterfly properly to the targetPosition?
Thanks!
Script1:
using UnityEngine;
using System.Collections;
public class ButtMove : MonoBehaviour {
private Vector3 targetPosition;
private Vector3 targetPos;
public void Start(){
**Vector3 targetPos = transform.position + Random.insideUnitSphere * 10;**
**targetPosition.x = targetPos.x;**
**targetPosition.y = targetPos.y;**
**targetPosition.z = 0f;**
Debug.Log ("targetposition = " + targetPosition.x + " - " + targetPosition.y);
}
public void Update(){
float speed = 2; //move towards targetPosition with this speed
Vector3 currentPosition = this.transform.position; //position of butterfly
//Debug.Log ("currentposition= " + currentPosition);
//first, check to see if we're not yet close to the target
if (Vector3.Distance (currentPosition, targetPosition) > .1f) {
Vector3 directionOfTravel = targetPosition - currentPosition;
//now normalize the direction, since we only want the direction information
directionOfTravel.Normalize ();
//scale the movement on each axis by the directionOfTravel vector components
this.transform.Translate (
(directionOfTravel.x * speed * Time.deltaTime),
(directionOfTravel.y * speed * Time.deltaTime),
(directionOfTravel.z * speed * Time.deltaTime),
Space.World);
}
}
}
Script2 only difference to script 1 is in Start():
public void Start(){
**Vector3 targetPosition = transform.position + Random.insideUnitSphere * 10;
targetPosition.z = 0f;**
Debug.Log ("targetposition = " + targetPosition.x + " - " + targetPosition.y);
}