[Unity]物体在屏幕内随机移动

  要求物体在屏幕内随机移动,但不能超出屏幕范围,那么需要注意两点:

    1.获取屏幕坐标,才能对物体移动加以限制。

    2.屏幕坐标和世界坐标的转换。

  可以直接使用Screen.heightScreen.width获取屏幕的尺寸,而不是直接写死尺寸,否则在不同分辨率的设备上使用效果会有差异。

 

  代码:

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using Random = UnityEngine.Random;
 5 
 6 public class RandomMove : MonoBehaviour
 7 {
 8 
 9     private float speed;
10     private Vector3 targetPosition;
11     void Start()
12     {
13         speed = 0.1f;
14         targetPosition = Camera.main.ScreenToWorldPoint(new Vector3(Random.Range(0f, Screen.width), Random.Range(0f, Screen.height)));
15 
16     }
17 
18     void Update()
19     {
20         RandomMoveFlower();
21     }
22     private void RandomMoveFlower()
23     {
24         transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
25     }
26 }

 

  最开头写的using Random=UnityEngine.Random;是为了之后直接写Random就好,而无需写成UnityEngine.Random的形式,省事。

  Camera可以直接调用其功能,无需事先声明了。

  Vector3和Vector2无论是在2D还是3D都可以使用,区别就是z轴坐标嘛,根据实际需求来设置。

  Time.deltaTime的作用可以自行百度,主要是为了去不同设备执行速率的差异化,换句话说就是让不同性能的电脑运行起来效果是一样的。

 

posted @ 2021-07-05 10:29  锤子猫  阅读(1589)  评论(0编辑  收藏  举报