You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新手求教:如何让物体始终缓慢朝向目标物体移动?

Unity收集类游戏实现步骤指导

一、玩家角色操控

  • 创建玩家对象:在Hierarchy窗口右键→2D Object→Sprite,导入你的玩家Sprite并赋值给该对象;添加Rigidbody2D组件,设置Body Type为Dynamic、Gravity Scale设为0(避免自动下落);再添加BoxCollider2D或CircleCollider2D作为碰撞体。
  • 编写移动脚本:右键→Create→C# Script,命名为PlayerMovement,代码如下:
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    private Rigidbody2D rb;
    private Vector2 movement;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        // 获取方向键/WASD输入
        movement.x = Input.GetAxis("Horizontal");
        movement.y = Input.GetAxis("Vertical");
    }

    void FixedUpdate()
    {
        // 应用移动逻辑
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    }
}
  • 把脚本拖到玩家对象上,运行游戏就能用方向键或WASD控制移动。

二、道具收集系统

  • 创建道具对象:右键→2D Object→Sprite,导入道具Sprite;添加BoxCollider2D并勾选Is Trigger;创建Collectible脚本:
using UnityEngine;

public class Collectible : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        // 检测碰撞对象是否为玩家
        if (other.CompareTag("Player"))
        {
            Destroy(gameObject); // 收集后销毁道具
            // 这里可以加分数统计逻辑,比如调用玩家脚本里的加分方法
        }
    }
}
  • 给玩家对象设置标签:选中玩家,在Inspector窗口的Tag下拉框选Player(没有就新建);把道具脚本拖到道具对象上,复制多个道具放到场景里,玩家碰到就会自动收集。

三、追踪敌人实现

  • 创建敌人对象:右键→2D Object→Sprite,导入敌人Sprite;添加Rigidbody2D组件,设置Body Type为Dynamic、Gravity Scale为0;添加CircleCollider2D(如果要做碰撞伤害就不勾Is Trigger,纯追踪可以勾上)。
  • 编写追踪脚本EnemyChase:
using UnityEngine;

public class EnemyChase : MonoBehaviour
{
    public float chaseSpeed = 2f;
    private Transform player;
    private Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        // 通过Player标签找到玩家对象
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }

    void FixedUpdate()
    {
        if (player == null) return; // 防止玩家对象被销毁时报错

        // 计算朝向玩家的单位方向向量
        Vector2 direction = (player.position - transform.position).normalized;
        // 移动敌人
        rb.MovePosition(rb.position + direction * chaseSpeed * Time.fixedDeltaTime);

        // 可选:让敌人Sprite朝向玩家
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
    }
}
  • 把脚本拖到敌人对象上,运行游戏后敌人就会缓慢朝向玩家移动。

内容的提问来源于stack exchange,提问作者Beachy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:12:22