How to move an Object in a path?
Hi All,
What I am trying here is, to move a GameObject in a particular path,
I have a straight line of path(in form of cubes), I just want my Player object to travel from one cube point to another in a path.
For Example :
Consider my player is in Cube-2, one pressing two, he should move two more blocks and go to Cube-4, so his path is, [ Cube-3, Cube-4].
The below is my code, but the problem here is, my player object is only moving a little from his current position.
Please help me on this, what am I doing wrongly?
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
ArrayList path;
private Animator animator;
private int currentPosition;
private string currentAnim;
void Start () {
animator = GetComponent<Animator> ();
currentPosition = 1;
transform.position = GameObject.Find ("Cube-1").transform.position;
currentAnim = null;
playAnimation("unarmed_idle");
}
void FixedUpdate () {
ArrayList path = CalculatePath ();
if (path != null) {
playAnimation("walk");
// Move the player from one point to other
foreach(GameObject pathPoint in path)
{
MoveToPosition (pathPoint.transform);
}
playAnimation("idle");
} else {
playAnimation("idle");
}
}
/**
* Calculates the points from current position to end position
*/
ArrayList CalculatePath(){
ArrayList path = null;
string keyPressed = Input.inputString;
int moveBy = -1;
switch (keyPressed) {
case "1":
moveBy = 1;
break;
case "2":
moveBy = 2;
break;
case "3":
moveBy = 3;
break;
default:
break;
}
if (moveBy != -1) {
path = new ArrayList (0);
int endPosition = currentPosition + moveBy;
// Find the GameObjects from current to end position
for(int i = currentPosition + 1; i <= endPosition; i++){
path.Add(GameObject.Find("Cube-" + i));
}
currentPosition += moveBy;
}
return path;
}
void MoveToPosition(Transform target){
Vector3 currentPosition = transform.position;
Vector3 targetPosition = target.position;
transform.position = Vector3.MoveTowards (currentPosition, targetPosition, Time.deltaTime * 2f);
}
void playAnimation(string animation){
if (currentAnim != animation) {
currentAnim = animation;
animator.Play(currentAnim);
}
}
}
Your answer
Follow this Question
Related Questions
Javascript Script for Object Follow? 0 Answers
How to create Curve between two points using **Vector3.MoveTowards**? 0 Answers
Have an object move towards another object until it hits a certain spot. 1 Answer
NPC Movement 0 Answers
Move Character to touched Position 2D (Without RigidBody and Animated Movement) 1 Answer