Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Junker · Sep 14, 2013 at 11:41 PM · c#2dtransformnewbie

how to make the player stay within screen in a simple 2d game. C#

So i just got into unity, i moved over from LibGdx(java) and everything is really new to me. I'm just trying to make a square move around a screen with a simple script. But i can't seem to figure out how to make it stay within the screen limits(pretty sure it's simple and i'm just stupid) i'm just testing it out by only using it on the right side on the screen, but shouldn't this work:

public class SquareScript : MonoBehaviour {

 private float moveSpeed = 10f;
 

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
     Vector3 playerPos = transform.position;
     
    if(Input.GetKey("left"))
         transform.position -= Vector3.right * moveSpeed * Time.deltaTime;
 
    if(Input.GetKey("right"))
         transform.position += Vector3.right * moveSpeed * Time.deltaTime;
     
    if(Input.GetKey("up"))
         transform.position += Vector3.up * moveSpeed * Time.deltaTime;    
     
    if(Input.GetKey("down"))
         transform.position -= Vector3.up * moveSpeed * Time.deltaTime;
     
    if(playerPos.x > Screen.width){
         playerPos.x = Screen.width;
         transform.position = playerPos;    
 
     }
 }    

}

it doesn't seem to work at all, also. If anybody know any decent turtorials on simple 2d scripting in unity, that would be awesome. Any help is GREATLY appreciated!

Thanks a lot

Comment
Add comment · Show 8
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image meat5000 ♦ · Sep 14, 2013 at 11:45 PM 0
Share

http://docs.unity3d.com/Documentation/ScriptReference/Camera.html

Try ScreenToWorld/WorldToScreen functions on the camera script reference, above. In a moving camera scene this can be useful. Alternatively, $$anonymous$$athf.Clamp could help you out.

avatar image ForgeStudios · Sep 15, 2013 at 12:05 AM 0
Share

@meat5000, the question is about making the character move. First question Junker, what axis do you want your character to move along? Also you say 2D, is this overhead 2D or sidescroller 2D, it does matter.

avatar image Benproductions1 · Sep 15, 2013 at 02:13 AM 0
Share

Please format your code. If you don't know how, watch the tutorial video on the right

avatar image ForgeStudios · Sep 15, 2013 at 02:16 AM 0
Share

What tutorial video on the right?

avatar image Benproductions1 · Sep 15, 2013 at 02:21 AM 0
Share

@ForgeStudios, forgive my sarcasm, but seriously:
Take a look at your Screen.
Look at the webpage in your browser
Look at the right side of the webpage
read
read some more
find "Unity Answers tutorial video!"
click on link

Show more comments

5 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by supernat · Sep 15, 2013 at 05:04 AM

If you are working in an orthogonal view or top-down perspective, you can simplify the problem by making your Ortho equal to your screen space dimensions. In other words, the issue you are having here is that the playerPos is in world space, but if you're camera is not configured so that world space X value at the right of the screen is equal to the Width (in pixels) of your viewport, then you can't use the playerPos with the Screen values.

Since the Editor doesn't allow you to set the left/right/top/bottom of your Orthographic projection to the specific pixel resolution you intend to run at, and I don't know what the Editor Camera's Size property actually reflects, the approach I would use is call:

Camera.ScreenToWorldPoint()

This will transform a screen point into the world point. Pass the right/left/top/bottom screen points in to find the correlating world point. Then compare that world point to the value of playerPos in your code above.

You will also want to add in the half-size of the box so that the entire box remains on screen. The following is an example to test the right side of the screen. It assumes X axis is positive to the right and that you are doing this in a non-static function as part of a MonoBehaviour-based script. Also note this should be optimized to determine the box size and world positions in the Start() method if possible:

 Vector3 wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));
 float half_sz = gameObject.renderer.bounds.size.x/2;
 if(playerPos.x > (wrld.x - half_sz))

I tried to make sure this is valid code, but if you have any errors here, let me know and I'll correct.

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Junker · Sep 15, 2013 at 10:42 PM 0
Share

hey, i tried this. It gives me this error: http://puu.sh/4sm9m.png

with this code: public class SquareScript : $$anonymous$$onoBehaviour { private float moveSpeed = 10f; Vector3 wrld; float half_sz;

     // Use this for initialization
     void Start () {
         Vector3 wrld = gameObject.camera.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));
         float half_sz = gameObject.renderer.bounds.size.x/2;
         
     }
     
     // Update is called once per frame
     void Update () {
         Vector3 playerPos = transform.position;
         
        if(Input.Get$$anonymous$$ey("left"))
             transform.position -= Vector3.right * moveSpeed * Time.deltaTime;
     
        if(Input.Get$$anonymous$$ey("right"))
             transform.position += Vector3.right * moveSpeed * Time.deltaTime;
         
        if(Input.Get$$anonymous$$ey("up"))
             transform.position += Vector3.up * moveSpeed * Time.deltaTime;    
         
        if(Input.Get$$anonymous$$ey("down"))
             transform.position -= Vector3.up * moveSpeed * Time.deltaTime;
         
        if(playerPos.x > (wrld.x - half_sz))
             playerPos.x = wrld.x - half_sz;
     }    
 }
avatar image supernat · Sep 15, 2013 at 11:10 PM 0
Share

Sorry about that, I updated it. It should be Camera.main.ScreenToWorldPoint(...). You would only do gameObject.camera if the script was attached to a game object with a Camera script. Using Camera.main will return the first enabled camera with Tag $$anonymous$$ainCamera.

avatar image Junker · Sep 16, 2013 at 01:44 PM 0
Share

gosh, i'm still a bit confused. This are my errors, any idea of what i'm doing wrong? http://puu.sh/4sN1T.png

I really appreciate your effort here.

avatar image vexe · Sep 16, 2013 at 04:28 PM 0
Share

You're trying to access a non-existent Camera component in Square - So add one.

avatar image supernat · Sep 17, 2013 at 03:36 AM 0
Share

Did you update the code to the following?

 // Use this for initialization
 void Start () {
    Vector3 wrld = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0.0f, 0.0f));
     float half_sz = gameObject.renderer.bounds.size.x/2;

You should not want to access a camera on the Square but to access the main camera in the scene. $$anonymous$$ake sure your main camera in the scene is tagged $$anonymous$$ainCamera.

avatar image
4

Answer by vexe · Sep 15, 2013 at 05:26 AM

Solving your problem and answering your question about a 2D tutorial, watch this series from quill18creates about a 2D brick game, I'm sure your problem is addressed there - Really great tuts he got, very good programmer, very friendly to new-comers and explains things in good depth.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by nickkorage · Aug 15, 2016 at 03:03 PM

I created an empty game object attached a box collider to where I didn't want my player to go. I found that to be extremely easy and straight forward

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by sikander11 · Jul 28, 2017 at 04:13 AM

@nickkorage collider doesnt work when object hit collider it moves.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Akki_8090 · Jun 29, 2018 at 10:09 AM

I made the edges on 4 sides by taking a quad and add a Rigidbody2D and box collider2D to it. But still in my game, ball goes beyond this edges when it cross the speed I mentioned it. Any suggestions for it?

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Player Respawn Rotation Troubles 1 Answer

Please Help - 2D Collisions Without Unity's Physics 1 Answer

Distribute terrain in zones 3 Answers

Setting my position to the position of a gameobject 0 Answers

Random Y Axis Direction On Prefab Within Boundaries (C#) 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges