Question by
KickOlaf · Oct 22, 2016 at 04:30 PM ·
scripting problemphysics
Making a ball move towards an object.
So..... I've been trying to make spheres roll towards selected targets. But they're not doing what I want them to do. For instance: most of the spheres just thrust themselves into the ground.
I tried to disable the y axis for the balls, but it does not work 'completely'.
Here's my code:
using UnityEngine;
using System.Collections;
public class AiBehaviour : MonoBehaviour {
public GameObject Target;
public float speed;
public float health;
public GameObject[] BlueUpdateControl;
public GameObject[] GreenUpdateControl;
private Rigidbody MyRigid;
private Collider colid;
private float Distance;
// Use this for initialization
void Start () {
BlueUpdateControl = GameObject.FindGameObjectsWithTag("Green");
GreenUpdateControl = GameObject.FindGameObjectsWithTag("Blue");
Target = null;
Distance = Mathf.Infinity;
MyRigid = gameObject.GetComponent<Rigidbody>();
colid = gameObject.GetComponent<Collider>();
}
// Update is called once per frame
void Update () {
foreach (GameObject Green in GreenUpdateControl)
{
Vector3 diff = Green.transform.position - transform.position;
float curDistance = diff.sqrMagnitude;
if(curDistance < Distance)
{
Target = Green;
Distance = curDistance;
}
}
if (health <= 0)
{
Target = null;
Destroy(gameObject);
}
}
void FixedUpdate()
{
float Hori;
float Verti;
Hori = Input.GetAxis("Horizontal");
Verti = Input.GetAxis("Vertical");
Vector3 FakeForward = new Vector3(Hori, 0.0f, Verti);
if (Target)
{
MyRigid.AddForce(FakeForward * speed * 10);
}
}
void OnCollisionEnter(Collision col)
{
if (gameObject.tag == "Green" && col.gameObject.tag == "Blue")
{
health -= Time.deltaTime;
colid.enabled = false;
colid.enabled = true;
}
if (gameObject.tag == "Blue" && col.gameObject.tag == "Green")
{
health -= Time.deltaTime;
colid.enabled = false;
colid.enabled = true;
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612095216im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to move a kinematic rigidbody with touch? 0 Answers
Collider fires consistently, but Trigger does not? 0 Answers
Can I ignore part of a vector3 for physics reasons? 0 Answers
How to make sphere 'stick' to inside of hollow cylinder 0 Answers
Multiplayer vehicle game - physics or not to physics 0 Answers