- Home /
Trying to get my pong AI to work
So I am a total beginner in coding. I am trying to get my Pong AI to work and I am using the Vector3.MoveTowards. I have searched for people with similar problems but often I don't understand the answers given. Or the answer is given in Java and I don't know how to convert it to c#.
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
Transform Ball;
public float speed = 10;
float movey;
void Start()
{
Ball = GameObject.FindGameObjectWithTag ("Ball").transform;
}
// Update is called once per frame
void Update ()
{
Vector3 giPos = Ball.transform.position;
giPos.y = movey;
Ball.transform.position = giPos;
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, movey, step);
}
}
Anyway, this is my code so far. It returns an compiler error in unity saying: CS1502: The best overloaded method match for UnityEngine.Vector3.MoveTowards(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments And also: CS1503: Argument
#2' cannot convert float' expression to type
UnityEngine.Vector3'
I understand that the "movey" thing is what is causing the error but I am at a complete loss on how to fix it. I feel stupid for asking but I'm banging my head against the wall. Feels like I have tried everything.
Answer by shay4545 · Jul 26, 2015 at 07:23 PM
the problem is that movey is a float and Vector3.MoveTowards requires a Vector3 instead of a float where movey is. So an easy fix would be to add:
Vector3 newPos = new Vector3(someXValue, movey, someZValue);
and then replace movey in the Vector3.Movetowards with newPos. Also, you might want to change:
giPos.y = movey
to
movey = giPos.y
Thank you so much for the help! This solved it for me. Just out of curiosity, why is it that in
Vector3 newPos = new Vector3(someXValue, movey, someZValue);
I get an compiler error when i put for example 8.5 as the x value. Works great as long as I use a whole number like 7,8 or 9. Not a problem, just curious. :)
Since 8.5 is not a whole number, you mst put an f after it to indicate it is a float. Whole numbers are ints, so they dont need the f after. Change it to 8.5f
Aha I see, thank you so much for the explanation. You have helped me a lot, keep up the good work! thumbsup