gpt4 book ai didi

c# - 试图在 unity3d 中将游戏对象保持在屏幕左右边界内

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:24 25 4
gpt4 key购买 nike

我的游戏对象有以下代码:

private float screenx;
Vector3 playerPosScreen;
void Start () {
screenx=Camera.main.pixelWidth-renderer.bounds.size.x ;
}

void update(){
playerPosScreen = Camera.main.WorldToScreenPoint(transform.position);
if (playerPosScreen.x >= screenx) {
//playerPosScreen.x=screenx;
transform.position=new Vector3 (screenx, transform.position.y,transform.position.z);
}
//txt.text = playerPosScreen.x.ToString();
else if(playerPosScreen.x<=renderer.bounds.size.x){
transform.position=new Vector3 (renderer.bounds.size.x, transform.position.y,transform.position.z);
}
}

我正在开发一个带有orthographic 相机的2D 游戏,我的问题是游戏对象一直在屏幕外,我是不是漏掉了什么?

最佳答案

经过一些研究,我发现了一个解决方案希望对我来说效果很好:

Vector3 playerPosScreen;
Vector3 wrld;
float half_szX;
float half_szY;
void Start () {
wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));
half_szX = renderer.bounds.size.x / 2;
half_szY = renderer.bounds.size.y /2 ;
}
void Update () {
playerPosScreen = transform.position;
if (playerPosScreen.x >=(wrld.x-half_szX) ) {
playerPosScreen.x=wrld.x-half_szX;
transform.position=playerPosScreen;
}
if(playerPosScreen.x<=-(wrld.x-half_szX)){
playerPosScreen.x=-(wrld.x-half_szX);
transform.position=playerPosScreen;
}
}

关于c# - 试图在 unity3d 中将游戏对象保持在屏幕左右边界内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330252/

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