Physics2D









How do I use Physics2 D
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: JumpAndRunMovement.cs Copy
94     void UpdateIsGrounded()
95     {
96         Vector2 position = new Vector2( transform.position.x, transform.position.y );
97
98         RaycastHit2D hit = Physics2D.Raycast( position, -Vector2.up, 0.1f, 1 << LayerMask.NameToLayer( "Ground" ) );
99
100         m_IsGrounded = hit.collider != null;
101         m_Animator.SetBool( "IsGrounded", m_IsGrounded );
102     }
File name: PlayerMoveScript.cs Copy
50  void Update () {
51
52   grounded = Physics2D.OverlapCircle(groundCheck.position, groundChecked, isGround);
53
54   if(transform.position.x > speedCount) {
55    speedCount += speedIncrease;
56    speedIncrease = speedIncrease * speedMultiplier;
57    moveSpeed = moveSpeed * speedMultiplier;
58   }
59
60   rigidbody.velocity = new Vector2 (moveSpeed, rigidbody.velocity.y);
61
62   if(Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) {
63
64    if(grounded) {
65     rigidbody.velocity = new Vector2 (rigidbody.velocity.x, jumpForce);
66     anim.SetTrigger ("Jump");
67     stopJumping = false;
68    }
69   }
70
71   if((Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0)) && !stopJumping) {
72    if(jumpTimeCounter > 0) {
73     rigidbody.velocity = new Vector2 (rigidbody.velocity.x, jumpForce);
74     jumpTimeCounter -= Time.deltaTime;
75    }
76   }
77
78   if(Input.GetKeyUp (KeyCode.Space) || Input.GetMouseButtonUp(0)) {
79    jumpTimeCounter = 0;
80    stopJumping = true;
81   }
82
83   if(grounded) {
84    jumpTimeCounter = jumpTime;
85   }
86
87
88   scoreCount += pointsPerSeconds = Time.deltaTime;
89
90   if(scoreCount > highScoreCount) {
91    highScoreCount = scoreCount;
92
93   }
94   scoreText.text = "Score: " + Mathf.Round(scoreCount);
95
96  }
File name: PlayerCtrl.cs Copy
37     void Update () {
38         isGrounded = Physics2D.OverlapBox(new Vector2(feet.position.x, feet.position.y), new Vector2(boxWidth, boxHeight), 360.0f, whatIsGround);
39
40         float playerSpeed = Input.GetAxisRaw("Horizontal"); // value will be 1, -1 or 0
41
42         playerSpeed *= speedBoost;
43
44         if (playerSpeed != 0)
45             MovePlayer(playerSpeed);
46         else
47             StopMoving();
48
49         if (Input.GetButtonDown("Jump"))
50             Jump();
51
52         if (Input.GetButtonDown("Fire1"))
53         {
54             FireBullets();
55         }
56
57         ShowFalling();
58
59         if (leftPressed)
60             MovePlayer(-speedBoost);
61
62         if (rightPressed)
63             MovePlayer(speedBoost);
64     }
File name: Cannon.cs Copy
63  void TouchCannonShoot(){
64   if(Input.touchCount > 0){
65    Touch touch = Input.GetTouch (0);
66
67    touchPos = Camera.main.ScreenToWorldPoint (touch.position);
68
69    Vector2 touchRayHit = new Vector2 (touchPos.x, touchPos.y);
70
71    RaycastHit2D hit = Physics2D.Raycast (touchRayHit , Vector2.zero);
72
73    if(hit.collider != null){
74     if(hit.collider.CompareTag("Player")){
75      if(touch.phase == TouchPhase.Stationary){
76       if (shot != 0) {
77        UpdatePowerLevel ();
78        isCharging = true;
79       }
80      }else if(touch.phase == TouchPhase.Ended){
81       if (shot != 0) {
82        GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
83        newCannonBullet.transform.GetComponent ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
84        if (GameController.instance != null && MusicController.instance != null) {
85         if (GameController.instance.isMusicOn) {
86          audioSource.PlayOneShot (cannonShot);
87         }
88        }
89        shot--;
90        powerLevel.value = 0;
91        readyToShoot = false;
92        isCharging = false;
93       }
94      }
95     }
96    }
97
98    /*if(touch.phase == TouchPhase.Stationary){
99     if (shot != 0) {
100      UpdatePowerLevel ();
101     }
102    }else if(touch.phase == TouchPhase.Ended){
103     if (shot != 0) {
104      GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
105      newCannonBullet.transform.GetComponent ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
106      if (GameController.instance != null && MusicController.instance != null) {
107       if (GameController.instance.isMusicOn) {
108        audioSource.PlayOneShot (cannonShot);
109       }
110      }
111      shot--;
112      powerLevel.value = 0;
113      readyToShoot = false;
114     }
115    }*/
116
117   }
118  }
File name: MovingObject.cs Copy
34   protected bool Move (int xDir, int yDir, out RaycastHit2D hit)
35   {
36    //Store start position to move from, based on objects current transform position.
37    Vector2 start = transform.position;
38
39    // Calculate end position based on the direction parameters passed in when calling Move.
40    Vector2 end = start + new Vector2 (xDir, yDir);
41
42    //Disable the boxCollider so that linecast doesn't hit this object's own collider.
43    boxCollider.enabled = false;
44
45    //Cast a line from start point to end point checking collision on blockingLayer.
46    hit = Physics2D.Linecast (start, end, blockingLayer);
47
48    //Re-enable boxCollider after linecast
49    boxCollider.enabled = true;
50
51    //Check if anything was hit
52    if(hit.transform == null)
53    {
54     //If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination
55     StartCoroutine (SmoothMovement (end));
56
57     //Return true to say that Move was successful
58     return true;
59    }
60
61    //If something was hit, return false, Move was unsuccesful.
62    return false;
63   }

Download file with original file name:Physics2D

Physics2D 230 lượt xem

Gõ tìm kiếm nhanh...