【发布时间】:2020-10-18 09:41:32
【问题描述】:
我正在为我的学校项目制作一个简单的 2D 船舶游戏。现在,ai 将面向玩家并跟随他们一定距离,然后在足够近时旋转,以便它可以从船的每一侧向玩家开火。但是在我当前的代码中,敌人会在射击范围内向玩家侧身移动,这显然不应该发生。
那么我怎样才能让敌人只向前移动并保持与玩家垂直。
这是我当前的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public float speed, stopD, retreatD, Chase_range, distance,firing_range;
// declare player and enemy as transform to retrieve their positions
public Transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
Chase_range = 14;
firing_range = 10;
stopD = 6;
retreatD = 4;
}
// Update is called once per frame
void Update()
{
// Distance between the enemy and player positions
distance = (Vector2.Distance(transform.position, player.position));
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
if (distance > stopD)
{
// move towards the player if the distance is greater than stop distance
speed = 10;
}
else if (distance < stopD & distance > retreatD)
{
speed = 0;
}
else if (distance < retreatD)
{
// move away from the player if the distance is less than stop distance (avoid collision)
speed = -10;
}
if (distance > Chase_range)
{
// have to use vector3 since vector2 does not work with the z axis
// calculate the difference in the position vectors
Vector3 vectorToTarget = player.position - transform.position;
// Calculate the angle between the objects and convert the result to degrees
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
// convert the angle into a quaternion so that it can be used by slerp
Quaternion playerq = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, playerq, Time.deltaTime * speed);
}
if (distance < firing_range)
{
float Rfactor;
Vector3 vectorToTarget = player.position - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
if (angle < 0)
{
Rfactor = 90;
}
else if (angle > 0)
{
Rfactor = -90;
}
Quaternion playerq = Quaternion.AngleAxis(angle + Rfactor, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, playerq, Time.deltaTime * speed);
}
}
而且不要介意那些糟糕的 cmets,它是用于学校的。 任何其他关于代码的 cmets 也将不胜感激
【问题讨论】:
-
你可能在错误的轴上使用了 forward 属性,但我真的不明白是什么问题,你能澄清一下吗?
-
到目前为止,代码按预期运行,敌人旋转并朝玩家移动一定距离,然后当它靠近时旋转,使其与玩家垂直。我现在需要做的是让敌人和玩家一起移动,这样他们就可以继续开火了。
-
你能不能试着给他的运动添加一个偏移量到你喜欢的轴上?
标签: c# unity3d path-finding