gpt4 book ai didi

unity-game-engine - 检测 "player"是在屏幕中间的左边还是右边

转载 作者:行者123 更新时间:2023-12-02 16:10:03 24 4
gpt4 key购买 nike

您好,感谢您阅读本文。

我对 Unity 还很陌生,但不管怎样,我制作了一个小游戏,与马里奥和其他人的风格相同。一款你左右移动并跳跃来躲避敌人的游戏。

但是我遇到了一些代码问题,而且我似乎无法找到答案来帮助我解决它。

我需要检测玩家是否在屏幕中间向左或向右移动,这样我就知道相机是否需要向左或向右移动。

这是我迄今为止创建的相机脚本。

using UnityEngine;
using System.Collections;

public class CameraFunction : MonoBehaviour {

float ydir = 0f;
public GameObject player;
//for our GUIText object and our score
public GUIElement gui;
float playerScore = 0;

//this function updates our guitext object
void OnGUI(){
gui.guiText.text = "Score: " + ((int)(playerScore * 10)).ToString ();
}
//this is generic function we can call to increase the score by an amount
public void increaseScore(int amount){
playerScore += amount;
}
//Camera will be disabled when we load a level, set the score in playerprefs
void OnDisable(){
PlayerPrefs.SetInt ("Score",(int)(playerScore));
}

// Update is called once per frame
void Update () {
//check that player exists and then proceed. otherwise we get an error when player dies
if (player) {


if (player.transform.position.x > -1) {

//update our score every tick of the clock
playerScore += Time.deltaTime;

transform.position = new Vector3 (transform.position.x + 0.03f, transform.position.y, -10);
}
}
}
}

我的脚本仅检测“玩家”是否通过当前 View 的中间,然后开始移动。

希望您能理解我的意思,并能够帮助我。

更新:

如果你这样看,我们可以将屏幕分成 2 部分,即左侧和右侧部分,当然我们还有这 2 部分之间的中间部分。

人物/玩家从屏幕左侧开始,必须向右穿过 map 到达最终目标。

现在,当人经过屏幕中间并进入屏幕右侧时,相机将开始向右移动。但我无法让它检测到用户/玩家是否向后移动,那么他的相机必须“卡住”。

因此,如果玩家位置 > 屏幕的 50%(右侧)= 摄像机向右移动。如果玩家位置小于屏幕的 50%(左侧)= 摄像机“卡住”。

最佳答案

您可以在附加到相机的任何脚本组件中使用它:

    if(camera.WorldToScreenPoint(player.transform.position).x > Screen.width / 2){
Debug.Log("Player is right of the middle of the screen.");
}

其中 WorldToScreenPoint 正在将世界坐标转换为屏幕坐标。

关于unity-game-engine - 检测 "player"是在屏幕中间的左边还是右边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com