- Home /
object flying around randomly
Hi guys, I am having this problem with my Character I have applied a script to my character that allows it to follow a path that is by different targets, and this is the script.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Enemy : MonoBehaviour { public Transform[] target; public float speed;
private int current;
void Update()
{
if (transform.position != target[current].position)
{
Vector3 pos = Vector3.MoveTowards(transform.position, target[current].position, speed * Time.deltaTime);
GetComponent<Rigidbody>().MovePosition(pos);
}
else current = (current + 1) % target.Length;
}
}
When its is kinematic it slowly falls down, and when its of kinematic it fly's around randomly.
That looks O$$anonymous$$, actually.
Random guess - have you tried setting 'transform.position' ins$$anonymous$$d of 'GetComponent().$$anonymous$$ovePosition'?
If you are manually controlling the position of a $$anonymous$$inematic rigidbody, you don't need to move it via the RigidBody.
And as a $$anonymous$$or note, it's usually slightly more efficient to grab the RigidBody in Start and keep it in a variable than it is to call GetComponent each frame. As a general rule, try to only call GetComponent on occasional events (such as collisions, clicks etc.) and avoid calling every frame. It's a tiny performance cost - but it can seriously start adding up if you do it a lot :P
Your answer
Follow this Question
Related Questions
physics.OverlapSphere colliders 1 Answer
Painted trees do not take their prefab's collider 3 Answers
Why I can't see convex meshes in unity? 0 Answers
Problem with slopes on my terrain 1 Answer