Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question PhysicsWorld.ApplyLinearImpulse is not working

Discussion in 'Physics for ECS' started by ScottJame, Mar 17, 2023.

  1. ScottJame

    ScottJame

    Joined:
    Dec 11, 2017
    Posts:
    5
    Hi! I have some issue with the following code:
    Code (CSharp):
    1. using System;
    2. using Code.QTry.Components;
    3. using Unity.Entities;
    4. using Unity.Mathematics;
    5. using Unity.Physics;
    6. using Unity.Physics.Extensions;
    7. using Unity.Physics.Systems;
    8. using UnityEngine;
    9.  
    10. namespace Code.QTry.Systems
    11. {
    12.     [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
    13.     [UpdateAfter(typeof(PhysicsInitializeGroup))]
    14.     [UpdateBefore(typeof(PhysicsSimulationGroup))]
    15.     [RequireMatchingQueriesForUpdate]
    16.     public partial class ClickKeyAndAddImpulseSystem : SystemBase
    17.     {
    18.         protected override void OnUpdate()
    19.         {
    20.             if (!Input.GetKey(KeyCode.Space))
    21.                 return;
    22.             var world = SystemAPI.GetSingletonRW<PhysicsWorldSingleton>();
    23.             var deltaTime = SystemAPI.Time.fixedDeltaTime;
    24.             CompleteDependency();
    25.             foreach (var (clickKeyAndAddImpulse, entity) in SystemAPI.Query<RefRO<ClickKeyAndAddImpulse>>()
    26.                          .WithEntityAccess())
    27.             {
    28.                 var impulse = new float3(0f, 0f, 1f) * 10f * deltaTime;
    29.                 var index = world.ValueRW.PhysicsWorld.GetRigidBodyIndex(entity);
    30.                 world.ValueRW.PhysicsWorld.ApplyLinearImpulse(index, impulse);
    31.             }
    32.         }
    33.     }
    34. }
    I run the game and nothing happen when i click <space>. The package i use is Unity.Physics 1.0.0-pre.44

    Help! >...<
     

    Attached Files:

  2. krsevan

    krsevan

    Joined:
    Apr 5, 2016
    Posts:
    4
    I have the same issue, would be great if someone knew the answer :/
     
  3. krsevan

    krsevan

    Joined:
    Apr 5, 2016
    Posts:
    4
    Actually i found a solution but you can't use physics world singleton you need to use PhysicsVelocity and PhysicsMass. So what i did is
    Code (CSharp):
    1.  foreach (var (input, velocity, mass) in SystemAPI.Query<RefRO<PlayerInput>, RefRW<PhysicsVelocity>, RefRW<PhysicsMass>>())
    2.         {
    3.             float horizontal = input.ValueRO.move.x;
    4.             float vertical = input.ValueRO.move.y;
    5.             velocity.ValueRW.ApplyLinearImpulse(in mass.ValueRO, new float3(horizontal * 10f, 0f, vertical * 10f));
    6.         }
    Now you don't even need a physics world for it. It actually much cleaner, hope it helps