trying to make a follow player ai for my cube but he does not move

Updated on June 1, 2018 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on May 31, 2018

I am trying to make this game where 2 cubes fight. I am using cubes because ill get into better models ltr. the player moves and shoots with wasd and space. I want to make a ai that does the same thing as in moving and shooting. I am fairly new to learning about AI and wondered if someone could help me.

 

player scrips below

 

Enemy Ai script. (I want to include chasing player, and make it to move with wasd and fire with space like player)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.AI;

public class Player2Movement : MonoBehaviour
{
public Transform player;

void start()
{

}

void update()
{
if (Vector3.Distance(player.position, this.transform.position) < 10)
{
Vector3 direction = player.position – this.transform.position;
direction.y = 0;

this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), 0.1f);

if (direction.magnitude > 5)
{
this.transform.Translate(0, 0, 0.05f);
}
}
}
}

 

player scripts

movement

using UnityEngine;

public class playermovement : MonoBehaviour {

public Rigidbody rb;

//public float ff = 2000f;
public float movementspeed = 50f;

// Use this for initialization
void Start ()
{

}

// Update is called once per frame
void FixedUpdate ()
{
//rb.AddForce(0, 0, ff * Time.deltaTime);

if ( Input.GetKey(“d”) )
{
rb.AddForce(movementspeed * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}

if (Input.GetKey(“a”))
{
rb.AddForce(-movementspeed * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}

if (Input.GetKey(“w”))
{
rb.AddForce(0, 0, movementspeed * Time.deltaTime, ForceMode.VelocityChange);
}

if (Input.GetKey(“s”))
{
rb.AddForce(0, 0, -movementspeed * Time.deltaTime, ForceMode.VelocityChange);
}

}
}

spawning bullet

using UnityEngine;

public class shooting : MonoBehaviour
{
public GameObject prefab;
float distance = 1.0f;

float nextSpawnTime;
float spawndelay = 1;

bool ShouldSpawn()
{
return Time.time >= nextSpawnTime;
}

void Update()
{
if (ShouldSpawn())
{
Spawn();
}
}
void Spawn()
{
if (Input.GetKey(“space”))
{
nextSpawnTime = Time.time + spawndelay;
Instantiate(prefab, transform.position + transform.forward * distance, transform.rotation);
}

}
}

fire bullet

using UnityEngine;

public class Speed : MonoBehaviour {

public Rigidbody rbo;
public float ms = 50f;

void Update () {

if (Input.GetKey(“space”))
{
rbo.AddForce(transform.forward * ms);
}
}
}

  • Liked by
Reply
0 on June 1, 2018

Hey, simple unity AI can be achieved using a nav mesh, making the enemy cube a nav mesh agent and a moveTo() function. for your spawn script, if you place it on the AI you might want to make a different method for spawning since your current one is in update and uses a get input.

  • Liked by
Reply
Cancel