试图保持屏幕内的游戏对象左,右unity3d界限 [英] trying to keep a game object within the screen left and right bounds in unity3d
本文介绍了试图保持屏幕内的游戏对象左,右unity3d界限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的code波纹管我的游戏对象:
I have this code bellow for my gameobject :
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);
}
}
我正在开发一个 2D
游戏与拼写
相机,我的问题是游戏对象是继续走下去出来的画面,我在这里丢失的东西吗?
I'm developing a 2D
game with an orthographic
camera,my problem is the gameobject is keep on going out of screen , am i missing something here ?
推荐答案
经过一番研究,我发现了一个解决方案,希望优秀的工作与我:
After some research i found a solution wish worked excellent with me :
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;
}
}
这篇关于试图保持屏幕内的游戏对象左,右unity3d界限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文