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
0
Question by nalyd4 · Jan 28, 2012 at 07:42 PM · physicsgravitychangechanging

Changing gravity on collision

I'm making a game where players can walk on walls and I have this code allowing me to change gravity

var walkSpeed = 8.0; var walkBackwardSpeed = 4.0; var sidestepSpeed = 8.0; var gravity = 10.0; var maxVelocityChange = 10.0; var inAirControl = 0.1; var canJump = true; var jumpHeight = 2.0;

// added for run (set to Fire2. Change in Project Settings / Input if different desired.) var canRun = true; var runSpeed = 14.0; // negative values here makes game unhappy var runBackwardSpeed = 6.0; // negative values here makes game unhappy // var runSpeedChange = 4.0; // negative values here makes game unhappy

var canRunSidestep = true; var runSidestepSpeed = 12.0;

// added for keyboard rotation ('Horizontal' rotates instead of translates / strafe) /var canRotate = false; var rotateSpeed = 1.0; var rotateInAir = false; / private var grounded = false; private var groundVelocity : Vector3; private var capsule : CapsuleCollider; private var gravityDirection = Vector3(0,-1,0);

@script RequireComponent(Rigidbody, CapsuleCollider)

function Awake () { rigidbody.freezeRotation = true; rigidbody.useGravity = false; capsule = GetComponent(CapsuleCollider); }

function FixedUpdate () { if (grounded) { // Calculate how fast we should rotate // var rotation = Input.GetAxis("Horizontal") * rotateSpeed;

     // Set 'Horizontal' input based on rotate variable
     /*var targetVelocity = (canRotate) ? new Vector3(0, rotation, Input.GetAxis("Vertical")) 
     : new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));*/
     
     // Calculate how fast we should be moving

     targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

     targetVelocity = transform.TransformDirection(targetVelocity);
     if (Input.GetAxis("Vertical") > 0)
     {
         targetVelocity.x *= (canRun && Input.GetButton("Fire2")) ? runSpeed : walkSpeed;
     }
     else 
     { 
         targetVelocity.x *= (canRun && Input.GetButton("Fire2")) ? runBackwardSpeed : walkBackwardSpeed;
     }

     targetVelocity.z *= (canRunSidestep && Input.GetButton("Fire2")) ? runSidestepSpeed : sidestepSpeed;
     
     
     // Rotate if rotate is enabled
     /*if (canRotate)
     {
         transform.Rotate(0, rotation, 0);
     }
     */
     
     // Apply a force that attempts to reach our target velocity
     var velocity = rigidbody.velocity;
     var velocityChange = (targetVelocity - velocity) + groundVelocity;
     velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
     velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
     velocityChange.y = 0;
     rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
    
     // Jump
     if (canJump && Input.GetButton("Jump"))
     {
         //rigidbody.velocity = Vector3(velocity.x, CalculateJumpVerticalSpeed(), velocity.z);
     
         rigidbody.velocity = -gravityDirection * CalculateJumpVerticalSpeed();
     
     }
    
     grounded = false;
 }
 
 else
 {
     // Add in air
     
     // Calculate how fast we should rotate
     /*rotation = Input.GetAxis("Horizontal") * rotateSpeed;
     
     // Set 'Horizontal' input behavior based on whether we can rotate in air
     targetVelocity = (rotateInAir) ? new Vector3(0, rotation, Input.GetAxis("Vertical"))
     : new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
     */    
     targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

     targetVelocity = transform.TransformDirection(targetVelocity) * inAirControl;
     
     // Rotate if rotate in air is enabled.
     /*if (rotateInAir)
     {
         transform.Rotate(0, rotation, 0);
     }
     */
     rigidbody.AddForce(targetVelocity, ForceMode.VelocityChange);
 }
 
     
 rigidbody.AddForce(gravityDirection * gravity * rigidbody.mass);
 

}

function TrackGrounded (col : Collision) { var minimumHeight = capsule.bounds.min.y + capsule.radius; for (var c : ContactPoint in col.contacts) { if (c.point.y < minimumHeight) { //we track velocity for rigidbodies we're standing on if (col.rigidbody) groundVelocity = col.rigidbody.velocity; //and become children of non-rigidbody colliders else transform.parent = col.transform; grounded = true;

 if (col.tag == "XZdown")
     gravityDirection = Vector3(0,-1,0);
 else if (col.tag == "XYback")
     gravityDirection = Vector3(0,0,-1);
 else if (col.tag == "YZleft")
     gravityDirection = Vector3(-1,0,0);
 else if (col.tag == "XZup")
     gravityDirection = Vector3(0,1,0);
      
   }

}
}

//unparent if we are no longer standing on our parent function OnCollisionExit (col : Collision) { if (col.transform == transform.parent) transform.parent = null; }

function OnCollisionStay (col : Collision) { TrackGrounded (col); }

function OnCollisionEnter (col : Collision) { TrackGrounded (col);

}

function CalculateJumpVerticalSpeed () { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 jumpHeight gravity); }


I copied the code from 125here125 and tweaked it a bit but I can't figure out how to make it so that when a player collides with an object with the tag XZup, for example, to make the gravity pull that character upwards.

Comment
Add comment
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

4 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Berenger · Jan 28, 2012 at 08:15 PM

I haven't read a line of your code. Let's be honest, nobody will.

But I can still answer though. First you need to detect when the collision occurs (function OnCollisionEnter(Collision collisionInfo)), then you need to check the tag (if( collisionInfo.transform.tag == "XZup")) and finally you need to change the gravity. For the scene gravity, over here. For a single object gravity, over there.

Good luck.

Comment
Add comment · Show 2 · 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 rabbitfang · Jan 29, 2012 at 07:09 PM 0
Share

And if you are wondering why no one will read a line of your code....

You have not formatted it properly. Select all your code and click on the 1010 button.

avatar image nalyd4 · Jan 29, 2012 at 08:07 PM 0
Share

oh! That does make sense... I'll do that from now on. Thanks!

avatar image
0

Answer by nalyd4 · Jan 28, 2012 at 10:41 PM

function OnCollisionEnter (col : Collision) { TrackGrounded (col);

 if (col.tag == "XZdown")
     gravityDirection = Vector3(0,-1,0);
 else if (col.tag == "XYback")
     gravityDirection = Vector3(0,0,-1);
 else if (col.tag == "YZleft")
     gravityDirection = Vector3(-1,0,0);
 else if (col.tag == "XZup")
     gravityDirection = Vector3(0,1,0);
   

}

This is what I have for that section but it didn't work. It's supposed to be single object gravity.

Comment
Add comment · Show 3 · 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 Berenger · Jan 28, 2012 at 10:51 PM 0
Share

You need to track down what isn't working. Is the event thrown ? How can you access the tag from Collision when that class don't have it ? $$anonymous$$aybe you did a typo on the tag and need a default if ? Is gravityDirection affecting something ? PS : please use comments when it's not a solution to the problem.

avatar image nalyd4 · Jan 28, 2012 at 11:03 PM 0
Share

wait... the tags have to be in the class? How do I do that? I feel so silly now. -_-

avatar image Berenger · Jan 28, 2012 at 11:36 PM 0
Share

Well, Unity is only going to tell you that there is an error. Replace col.tag by col.transform.tag and you're good to go.

avatar image
0

Answer by nalyd4 · Jan 29, 2012 at 02:37 AM

YES! IT WORKED! Thank you!

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 nalyd4 · Jan 29, 2012 at 02:37 AM

The player's gravity can change now but I can't get the player to rotate with the gravity. For example if the player begins to fall up, the ground will still be down and the ceiling will still be up however what was originally the ground should instead be up. How would I do this?

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

6 People are following this question.

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

Related Questions

Faux Gravity Prolem? #2 2 Answers

How do i stop rigid bodies jumping? 1 Answer

Re-orienting Player after changing direction of Gravity 0 Answers

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How to make an axis always face an object? 2 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