- Home /
Inconsistant speed of object following raycast
So im creating a simple game and one component of the game is a greendot following the outside of the level. I got this working using a raycast in the middle which rotates and gives the position of collision the the gameobject.
The problem is that the speed is inconsistant at the moment since the distance between two collisions can be further distance if i have a slope. I also have the feeling that there should be a easier way to get the same result. What are your thoughts?
public class FollowPath : MonoBehaviour { Vector3 collisionPos; public GameObject greenDot;
void Update ()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up);
transform.Rotate(0.0f, 0.0f, 3);
if (hit.collider != null)
{
collisionPos = hit.point;
}
greenDot.transform.position = collisionPos;
}
}
Answer by OncaLupe · Oct 31, 2015 at 01:48 AM
My thought was to have a path the green dot follows. You can place empty game objects at each of the angles the walls make, store them in an array in the dot, and have it move from one to the next. This should give you constant movement no matter the direction, as well as allow more complex room shapes than a raycast would work with.
using UnityEngine;
using System.Collections;
public class GreenDotMover : MonoBehaviour
{
public Transform[] waypointPaths;
int currTarget;
Vector3 targetPosition;
public float moveSpeed = 1f;
float arrivalDistance = 0.1f;
void Start()
{
//Move to the first waypoint, then set target to the second
transform.position = waypointPaths[0].position;
currTarget = 1;
targetPosition = waypointPaths[1].position;
}
void Update()
{
//Move toward the next waypoint. When we reach it, get next waypoint
transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
if(Vector2.Distance(transform.position, targetPosition) < arrivalDistance)
{
++currTarget;
if(currTarget >= waypointPaths.Length)
currTarget = 0;
targetPosition = waypointPaths[currTarget].position;
}
}
}
Your answer

Follow this Question
Related Questions
Why are gravity rigidbodies so performance costly? 1 Answer
complexity of hierarchy affects performance? 1 Answer
Low CPU and GPU utilization with Vsync disabled, in blank scene GPU Usage "other" spikes to ~20ms 1 Answer
Reading Profiler Results 1 Answer
1024 x 1024 or 2048 x 2048 for main character, what is the best performance/looks 2 Answers