Gameplay / ObjectLauncher
ObjectLauncher Class ​
Projectile launcher
Throwing object launcher is a common mechanism in games used to simulate the launch and flight of throwing objects. It allows players or game characters to launch objects to the target location by selecting the appropriate direction and force.
Imagine standing on a balcony with a small ball in your hand and hoping to throw it at a target. The projectile launcher is like your arm and hand. It helps you control the launch of the ball. You can adjust the direction and strength of your arm so that the sphere flies in a specific way.
Once the player decides on the direction and force of the launch, the projectile launcher will launch the projectile. Throwing objects will start flying according to the speed and launch angle set by the launcher. It will pass through an arc-shaped path in the air and be affected by gravity and other physical effects.
ObjectLauncher For the transmitter. The instance emitted by the launcher is called a projectile instance ProjectileInst. The actual launched object is attached to the projectile instance.
When spawnProjectileInstanceLaunch launches the launch, the GameObject ID is passed in (note the object ID in the scene, not the asset ID), the projectile instance drags the incoming model to move, and the transmitter acts as the launch terminal to maintain the parameters related to the projectile launch.
The call end of the transmitter API can be a server or a client; There are three ways to launch projectile: 1. Double ended projectile 2. All client projectile 3. single client projectile
Should the Object Launcher object be loaded on the client or server side?
- Server side
Dynamically generate a projectile launcher at the server to obtain a sync projectile launcher object at each end. Modifying the attributes of the projectile launcher will be synchronized to all clients.
After adding a projectile launcher delegation to the server, the delegation will only be executed on the server, provided that the launcher exists on the server.
When the server call the launch API, generate a double ended projectile to launch according to the current transmitter property of the server. If the launch object cannot be found at the server (it may be a single client projectile), return directly to find it (the launch object is a double ended object), and mount the launch object on the projectile. The collision and trajectory of the dual ended projectile are calculated by the server, which is based on the calculation results of the server.
- client
Dynamically generating a projectile launcher on the client side can only obtain one local projectile launcher object and only supports local launch.
After adding a callback locally, the callback will only execute locally, provided that the emitter exists locally.
Call broadcast transmission locally: Generate single ended projectiles based on the current local transmitter properties, and notify the server to broadcast other clients to generate single ended projectiles based on the current local transmitter properties. If the launch object cannot be found on the server, return directly and if it can be found (the launch object is a dual ended object), hang the projectile.
In addition, there are parameters such as control launcher's initial launch speed, gravity, projectile radius, etc.
Hierarchy ​
↳
ObjectLauncher
Table of contents ​
Properties ​
onProjectileHit: MulticastDelegate <(projectile : ProjectileInst , hitGameObject : GameObject , hitResult : HitResult ) => void > |
---|
Trigger binding function when throwing object hits object |
onProjectileHomingFail: MulticastDelegate <(projectile : ProjectileInst ) => void > |
When the projectile fails to track the target (i.e. is destroyed), the binding function is triggered |
onProjectileLifeEnd: MulticastDelegate <(projectile : ProjectileInst ) => void > |
Trigger binding function when the lifecycle of the projectile ends (i.e. speed drops to 0, LifeSpan expires) |
onProjectileLifeStart: MulticastDelegate <(projectile : ProjectileInst ) => void > |
The binding function is triggered when the projectile generate instance. At this time, the instance has not started moving |
click
Properties ​
onBeforeDestroyDelegate: MulticastDelegate <() => void > other |
---|
Event callback before object destruction |
onCustomPropertyChange: Readonly <MulticastDelegate <(path : string , value : unknown , oldValue : unknown ) => void >> other |
Monitor custom attribute synchronization events |
onDestroyDelegate: MulticastDelegate <() => void > other |
Event callback after object destruction |
onPropertyChange: Readonly <MulticastDelegate <(path : string , value : unknown , oldValue : unknown ) => void >> |
Monitor system replicated events |
Accessors ​
acceleration(): number |
---|
The acceleration (cm/s) of the movement of the projectile, a positive value will accelerate the projectile and a negative value will decelerate. Default: 0, range: [-100000010000]. |
capsuleHalfLength(): number |
The projectile collision with the half length (cm) of the capsule body. If the half length is less than the radius, it is a sphere. Default: 50. Range: [1,1000]. |
capsuleRadius(): number |
The radius (cm) of the projectile colliding with the capsule body. Default: 25. Range: [1,1000]. |
collisionVelocityRetention(): number |
After the collision, the projectile maintains the ratio of the original speed. 0 represents. Default: 0.6. Range: [0,1]. |
gravityScale(): number |
The multiplier of the impact of world gravity on a projectile, where a positive value causes the projectile to fall, a negative value increases, and 0 causes the projectile to move in a straight line. Default: 1, range: [-10, 10]. |
initialSpeed(): number |
Initial velocity of the projectile (cm/s), default: 5000, range: [110000]. |
isRotationFollowsVelocity(): boolean |
Does the forward direction of the projectile (and the mounted object) always follow the direction of motion. True: Follow. False: Do not follow. default: true。 |
isShouldBounce(): boolean |
Determine whether the projectile can bounce back when it collides with other objects during its motion. True: Rebound. False: Penetration. default: true。 |
isShouldReplicateDelegates(): boolean |
Whether to broadcast when the projectile triggers the corresponding event (only the dual ended transmitter takes effect), true: broadcast. False: Local only |
lifeSpan(): number |
The maximum duration of the projectile's existence (s), 0 means there is no limit. Default: 10. Range: [0, 1000]. |
maxSpeed(): number |
The maximum movement speed of the projectile (cm/s), 0 means there is no limit. Default: 0, range: [0100000]. |
click
Accessors ​
actorFlagValue(): number other |
---|
Get object tags |
actorLevel(): number other |
Obtain Actor Level |
assetId(): string other |
Retrieve the UID of the resource currently being used by the object |
gameObjectId(): string other |
Get the unique identification of an object (a string that uniquely identifies an object). |
isDestroyed(): boolean other |
Has the current object been destroyed |
isReady(): boolean other |
Current object status |
localTransform(): Transform other |
Local transformation of the current object |
name(): string other |
Return the current object name |
netStatus(): NetStatus other |
Get the current object synchronization status |
parent(): GameObject other |
Retrieve the current parent object |
tag(): string other |
Get the tag of the current object |
worldTransform(): Transform other |
Current object world transformation |
Methods ​
predictedTrajectory(startPosition : Vector , startDirection : Vector , density : number , duration : number ): Vector [] other |
---|
Return a path point array based on predicted time and density. The rebound path after collision is not predicted. |
spawnProjectileInstanceLaunch(childObjectId : string , startPosition? : Vector , direction? : Vector , isAllClientLaunch? : boolean ): ProjectileInst other |
Projectile object generate according to the current parameters of the Object Launcher |
spawnProjectileInstanceLaunchToTarget(childObjectId : string , target : GameObject , targetingAcceleration? : number , startPosition? : Vector , direction? : Vector , isAllClientLaunch? : boolean ): ProjectileInst other |
Projectile object generate according to the current parameters of the Object Launcher |
click
Methods ​
addComponent<T : extends Script <T >>(constructor : (...args : unknown []) => T : extends Script <T >, bInReplicates? : boolean ): T : extends Script <T > other |
---|
Add a script component |
asyncGetChildByName(name : string ): Promise <GameObject > other |
Asynchronous search for sub objects based on their names |
asyncReady(): Promise <GameObject > other |
Return after the object is ready |
clone(gameObjectInfo? : GameObjectInfo ): GameObject other |
Copy Objects |
destroy(): void other |
delete object |
getBoundingBox(nonColliding? : boolean , includeFromChild? : boolean , outer? : Vector ): Vector other |
Get the size of the object's bounding box |
getBounds(onlyCollidingComponents : boolean , originOuter : Vector , boxExtentOuter : Vector , includeFromChild? : boolean ): void other |
Obtain object boundaries |
getChildByGameObjectId(gameObjectId : string ): GameObject other |
Search for sub objects based on gameObjectid |
getChildByName(name : string ): GameObject other |
Search for sub objects by name |
getChildByPath(path : string ): GameObject other |
Find sub objects according to path |
getChildren(): GameObject [] other |
Obtain sub objects |
getChildrenBoundingBoxCenter(outer? : Vector ): Vector other |
Get the center point of all child objects' bounding box (not including the parent object, if the parent object is unavailable, return [0,0,0]) |
getChildrenByName(name : string ): GameObject [] other |
Search for all sub objects by name |
getComponent<T : extends Script <T >>(constructor? : (...args : unknown []) => T : extends Script <T >): T : extends Script <T > other |
Get the component of the specified type |
getComponentPropertys<T : extends Script <T >>(constructor : (...args : unknown []) => T : extends Script <T >): Map <string , IPropertyOptions > other |
Get property of script component |
getComponents<T : extends Script <T >>(constructor? : (...args : unknown []) => T : extends Script <T >): T : extends Script <T >[] other |
Get all component of the specified type |
getCustomProperties(): string [] other |
Get all customize property |
getCustomProperty<T : extends CustomPropertyType >(propertyName : string ): T : extends CustomPropertyType other |
Get customize property |
getCustomPropertyChangeDelegate(property ): Readonly <MulticastDelegate <(path : string , value : unknown , oldValue : unknown ) => void >> other |
Event proxy triggered when a given object property is modified |
getPropertyChangeDelegate(property ): Readonly <MulticastDelegate <(path : string , value : unknown , oldValue : unknown ) => void >> other |
Event proxy triggered when a given object property is modified |
getVisibility(): boolean other |
Obtain whether the object is displayed |
isPrefabActor(): boolean other |
Return whether the current object is a prefabricated body |
moveBy(velocity : Vector , isLocal? : boolean ): void other |
Smoothly move an object over time according to a given velocity vector |
moveTo(targetPosition : Vector , time : number , isLocal? : boolean , onComplete? : () => void ): void other |
Smoothly move from the current position to the target position within the specified time |
rotateBy(rotation : Quaternion Rotation , multiplier : number , isLocal? : boolean ): void other |
Rotate the object smoothly over time according to the given rotation amount |
rotateTo(targetRotation : Quaternion Rotation , time : number , isLocal? : boolean , onComplete? : () => void ): void other |
Smoothly changes from the current rotation to the target rotation within the specified time |
scaleBy(scale : Vector , isLocal? : boolean ): void other |
Smoothly scale objects over time using a given scaling vector per second |
scaleTo(targetScale : Vector , time : number , isLocal? : boolean , onComplete? : () => void ): void other |
Smoothly changes from the current scale to the target scale within the specified time |
setAbsolute(absolutePosition? : boolean , absoluteRotation? : boolean , absoluteScale? : boolean ): void other |
Set whether the object localTransform is relative to the parent object or the world |
setCustomProperty(propertyName : string , value : undefined CustomPropertyType ): void other |
Set custom attributes |
setVisibility(status : boolean PropertyStatus , propagateToChildren? : boolean ): void other |
Set whether the object is displayed |
stopMove(): void other |
Interrupt further movement of moveTo() and moveBy() |
stopRotate(): void other |
Interrupt further rotation from rotateTo() or rotateBy() |
stopScale(): void other |
Interrupt further scale from ScaleTo() or ScaleBy() |
asyncFindGameObjectById(gameObjectId : string ): Promise <GameObject > other |
Asynchronous search for GameObject through gameObjectid |
asyncGetGameObjectByPath(path : string ): Promise <GameObject > other |
Asynchronously find objects through path |
asyncSpawn<T : extends GameObject <T >>(assetId : string , gameObjectInfo? : GameObjectInfo ): Promise <T : extends GameObject <T >> other |
Asynchronous construction of an object |
bulkPivotTo(gameObjects : GameObject [], transforms : Transform []): void other |
Batch set position |
findGameObjectById(gameObjectId : string ): GameObject other |
Search for objects through gameObjectid |
findGameObjectByName(name : string ): GameObject other |
Search for objects by name |
findGameObjectsByName(name : string ): GameObject [] other |
Search for objects by name |
findGameObjectsByTag(tag : string ): GameObject [] other |
Get objects through customize tag |
getGameObjectByPath(path : string ): GameObject other |
Search for objects through paths |
spawn<T : extends GameObject <T >>(assetId : string , gameObjectInfo? : GameObjectInfo ): T : extends GameObject <T > other |
Construct an object |
Properties ​
onProjectileHit ​
• onProjectileHit: MulticastDelegate
<(projectile
: ProjectileInst
, hitGameObject
: GameObject
, hitResult
: HitResult
) => void
>
Trigger binding function when throwing object hits object
Precautions
All projectile use the same callback. Please do not add event binding functions cyclically
onProjectileHomingFail ​
• onProjectileHomingFail: MulticastDelegate
<(projectile
: ProjectileInst
) => void
>
When the projectile fails to track the target (i.e. is destroyed), the binding function is triggered
Precautions
All projectile use the same callback. Please do not add event binding functions cyclically
Usage example: create a script and place it in the object bar, copy the following "Example_ObjectLauncher_OnHomingFail" code in the script to save, run the game, and generate a Object Launcher, a sphere for emission, and an NPC target in the scene. Bind the delegate function for the corresponding event to the transmitter. Press key "1" to launch sphere and track NPC. The object code is set as follows:
@Component
export default class Example_ObjectLauncher_OnHomingFail extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a sphere at world coordinates (200, 0, 25)
let ball = await GameObject.asyncSpawn("84121") as Model;
ball.worldTransform.position = new Vector(200, 0, 25);
// Generate an NPC asynchronously at world coordinates (20001000130) and destroy it after 2 seconds.
let target = Player.spawnDefaultCharacter();
target.worldTransform.position = new Vector(2000, 1000, 130);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1000
myLauncher.initialSpeed = 1000;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set collision speed attenuation to 0.5
myLauncher.collisionVelocityRetention = 0.5;
// Delegate binding function for transmitter tracking failure, and print information in case of tracking failure
myLauncher.onProjectileHomingFail.add((projectile) => {
console.log("Homing Fail");
});
// Add a 'LAUNCHTOTARGET' event listener sent by the client, shoot the ball diagonally upwards and track NPCs.
Event.addClientListener("LAUNCHTOTARGET", () => {
TimeUtil.delaySecond(1).then(() => {
target.destroy();
});
myLauncher.spawnProjectileInstanceLaunchToTarget(ball.gameObjectId, target, 2000, ball.worldTransform.position, new Vector(1, 0, 1));
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a button method: Press button "1" to send a "LAUNCHTOTARGET" event to the server and launch a ball to track the NPC.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCHTOTARGET");
});
}
}
}
@Component
export default class Example_ObjectLauncher_OnHomingFail extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a sphere at world coordinates (200, 0, 25)
let ball = await GameObject.asyncSpawn("84121") as Model;
ball.worldTransform.position = new Vector(200, 0, 25);
// Generate an NPC asynchronously at world coordinates (20001000130) and destroy it after 2 seconds.
let target = Player.spawnDefaultCharacter();
target.worldTransform.position = new Vector(2000, 1000, 130);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1000
myLauncher.initialSpeed = 1000;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set collision speed attenuation to 0.5
myLauncher.collisionVelocityRetention = 0.5;
// Delegate binding function for transmitter tracking failure, and print information in case of tracking failure
myLauncher.onProjectileHomingFail.add((projectile) => {
console.log("Homing Fail");
});
// Add a 'LAUNCHTOTARGET' event listener sent by the client, shoot the ball diagonally upwards and track NPCs.
Event.addClientListener("LAUNCHTOTARGET", () => {
TimeUtil.delaySecond(1).then(() => {
target.destroy();
});
myLauncher.spawnProjectileInstanceLaunchToTarget(ball.gameObjectId, target, 2000, ball.worldTransform.position, new Vector(1, 0, 1));
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a button method: Press button "1" to send a "LAUNCHTOTARGET" event to the server and launch a ball to track the NPC.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCHTOTARGET");
});
}
}
}
onProjectileLifeEnd ​
• onProjectileLifeEnd: MulticastDelegate
<(projectile
: ProjectileInst
) => void
>
Trigger binding function when the lifecycle of the projectile ends (i.e. speed drops to 0, LifeSpan expires)
Precautions
All throwing objects use the same callback, please do not loop to add event binding functions; The callback added by the client cannot guarantee whether the instance still exists when this delegation is triggered when launching a dual ended object
onProjectileLifeStart ​
• onProjectileLifeStart: MulticastDelegate
<(projectile
: ProjectileInst
) => void
>
The binding function is triggered when the projectile generate instance. At this time, the instance has not started moving
Precautions
All projectile use the same callback. Please do not add event binding functions cyclically
Accessors ​
acceleration ​
• | • | ||||
---|---|---|---|---|---|
The acceleration (cm/s) of the movement of the projectile, a positive value will accelerate the projectile and a negative value will decelerate. Default: 0, range: [-100000010000]. Returns ​
| The acceleration (cm/s) of the movement of the projectile, a positive value will accelerate the projectile and a negative value will decelerate. Default: 0, range: [-100000010000]. Parameters ​
|
capsuleHalfLength ​
• | • | ||||
---|---|---|---|---|---|
The projectile collision with the half length (cm) of the capsule body. If the half length is less than the radius, it is a sphere. Default: 50. Range: [1,1000]. Returns ​
| The projectile collision with the half length (cm) of the capsule body. If the half length is less than the radius, it is a sphere. Default: 50. Range: [1,1000]. Parameters ​
|
capsuleRadius ​
• | • | ||||
---|---|---|---|---|---|
The radius (cm) of the projectile colliding with the capsule body. Default: 25. Range: [1,1000]. Returns ​
| The radius (cm) of the projectile colliding with the capsule body. Default: 25. Range: [1,1000]. Parameters ​
|
collisionVelocityRetention ​
• | • | ||||
---|---|---|---|---|---|
After the collision, the projectile maintains the ratio of the original speed. 0 represents. Default: 0.6. Range: [0,1]. Returns ​
| After the collision, the projectile maintains the ratio of the original speed. 0 represents. Default: 0.6. Range: [0,1]. Parameters ​
|
gravityScale ​
• | • | ||||
---|---|---|---|---|---|
The multiplier of the impact of world gravity on a projectile, where a positive value causes the projectile to fall, a negative value increases, and 0 causes the projectile to move in a straight line. Default: 1, range: [-10, 10]. Returns ​
| The multiplier of the impact of world gravity on a projectile, where a positive value causes the projectile to fall, a negative value increases, and 0 causes the projectile to move in a straight line. Default: 1, range: [-10, 10]. Parameters ​
|
initialSpeed ​
• | • | ||||
---|---|---|---|---|---|
Initial velocity of the projectile (cm/s), default: 5000, range: [110000]. Returns ​
| Initial velocity of the projectile (cm/s), default: 5000, range: [110000]. Parameters ​
|
isRotationFollowsVelocity ​
• | • | ||||
---|---|---|---|---|---|
Does the forward direction of the projectile (and the mounted object) always follow the direction of motion. True: Follow. False: Do not follow. default: true。 Returns ​
| Does the forward direction of the projectile (and the mounted object) always follow the direction of motion. True: Follow. False: Do not follow. default: true。 Parameters ​
|
isShouldBounce ​
• | • | ||||
---|---|---|---|---|---|
Determine whether the projectile can bounce back when it collides with other objects during its motion. True: Rebound. False: Penetration. default: true。 Returns ​
| Determine whether the projectile can bounce back when it collides with other objects during its motion. True: Rebound. False: Penetration. default: true。 Parameters ​
|
isShouldReplicateDelegates ​
• | • | ||||
---|---|---|---|---|---|
Whether to broadcast when the projectile triggers the corresponding event (only the dual ended transmitter takes effect), true: broadcast. False: Local only Returns ​
| Whether to broadcast when the projectile triggers the corresponding event (only the dual ended transmitter takes effect), true: broadcast. False: Local only Parameters ​
|
lifeSpan ​
• | • | ||||
---|---|---|---|---|---|
The maximum duration of the projectile's existence (s), 0 means there is no limit. Default: 10. Range: [0, 1000]. Returns ​
| The maximum duration of the projectile's existence (s), 0 means there is no limit. Default: 10. Range: [0, 1000]. Parameters ​
|
maxSpeed ​
• | • | ||||
---|---|---|---|---|---|
The maximum movement speed of the projectile (cm/s), 0 means there is no limit. Default: 0, range: [0100000]. Returns ​
| The maximum movement speed of the projectile (cm/s), 0 means there is no limit. Default: 0, range: [0100000]. Parameters ​
|
Methods ​
predictedTrajectory ​
• predictedTrajectory(startPosition
, startDirection
, density
, duration
): Vector
[] other
Return a path point array based on predicted time and density. The rebound path after collision is not predicted.
Parameters ​
startPosition Vector | Launch starting position |
---|---|
startDirection Vector | Launch starting direction |
density number | The point density of the predicted results (in units/second), the larger the value, the finer the path points, and the higher the performance consumption. Range: (0, density * duration+1] type: floating-point number |
duration number | Predicted duration. Range: unrestricted type: floating point number |
Returns ​
Vector [] | The maximum number of path track points predicted is density * duration+1. |
---|
Precautions
If the returned array length is 1, the projectile may be stuck
spawnProjectileInstanceLaunch ​
• spawnProjectileInstanceLaunch(childObjectId
, startPosition?
, direction?
, isAllClientLaunch?
): ProjectileInst
other
Projectile object generate according to the current parameters of the Object Launcher
Parameters ​
childObjectId string | The ID of the emitting object. Range: The string length depends on the ID length. |
---|---|
startPosition? Vector | Launch start position default: position of the launch object |
direction? Vector | Launch starting direction default: Directly in front of the launch object |
isAllClientLaunch? boolean | Only valid when transmitting single client objects. Whether to broadcast to all client transmitting instances default: false |
Returns ​
ProjectileInst | Example of projectile |
---|
Precautions
Update other property after launch cannot affect the projectile launched this time
Example usage: Create a script and place it in the object bar. Copy and save the following code for "Exemplar_SpecificLauncher-ACcceleration" in the script. Run the game, and an object launcher and a rocket for launching will be generated in the scene. Press key "1" to launch the rocket. The setting object code is as follows:
@Component
export default class Example_ObjectLauncher_Acceleration extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a rocket at world coordinates (200, 0, 25)
let rocket = await GameObject.asyncSpawn("162807") as Model;
rocket.worldTransform.position = new Vector(2000, 0, 25);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1
myLauncher.initialSpeed = 1;
// Set the maximum launch speed to 1000
myLauncher.maxSpeed = 1000;
// Set the launch acceleration to 200
myLauncher.acceleration = 200;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set gravity scale to 0
myLauncher.gravityScale = 0;
// Set rotation not to follow speed direction
myLauncher.isRotationFollowsVelocity = false;
// The exercise time is 10 seconds
myLauncher.lifeSpan = 10;
// Add a 'LAUNCH' event listener sent by the client and launch the rocket upwards.
Event.addClientListener("LAUNCH", () => {
myLauncher.spawnProjectileInstanceLaunch(rocket.gameObjectId, rocket.worldTransform.position, new Vector(0, 0, 1));
rocket.localTransform.rotation = new Rotation(0, 90, 0);
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a key method: press key "1" to send a "LAUNCH" event to the server and launch a sphere.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCH");
});
}
}
}
@Component
export default class Example_ObjectLauncher_Acceleration extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a rocket at world coordinates (200, 0, 25)
let rocket = await GameObject.asyncSpawn("162807") as Model;
rocket.worldTransform.position = new Vector(2000, 0, 25);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1
myLauncher.initialSpeed = 1;
// Set the maximum launch speed to 1000
myLauncher.maxSpeed = 1000;
// Set the launch acceleration to 200
myLauncher.acceleration = 200;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set gravity scale to 0
myLauncher.gravityScale = 0;
// Set rotation not to follow speed direction
myLauncher.isRotationFollowsVelocity = false;
// The exercise time is 10 seconds
myLauncher.lifeSpan = 10;
// Add a 'LAUNCH' event listener sent by the client and launch the rocket upwards.
Event.addClientListener("LAUNCH", () => {
myLauncher.spawnProjectileInstanceLaunch(rocket.gameObjectId, rocket.worldTransform.position, new Vector(0, 0, 1));
rocket.localTransform.rotation = new Rotation(0, 90, 0);
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a key method: press key "1" to send a "LAUNCH" event to the server and launch a sphere.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCH");
});
}
}
}
spawnProjectileInstanceLaunchToTarget ​
• spawnProjectileInstanceLaunchToTarget(childObjectId
, target
, targetingAcceleration?
, startPosition?
, direction?
, isAllClientLaunch?
): ProjectileInst
other
Projectile object generate according to the current parameters of the Object Launcher
Parameters ​
childObjectId string | The ID of the emitting object. Range: string length depends on ID length |
---|---|
target GameObject | Track target |
targetingAcceleration? number | Tracking acceleration default: 10000 range: unlimited type: floating point |
startPosition? Vector | Launch start position default: position of the launch object |
direction? Vector | Launch starting direction default: Directly in front of the launch object |
isAllClientLaunch? boolean | Only valid when transmitting single client objects. Whether to broadcast to all client transmitting instances default: false |
Returns ​
ProjectileInst | Example of projectile |
---|
Precautions
Update other property after firing cannot affect the bullets fired this time; When calling method broadcast and tracking mode transmission on the server, it comes with a tracking acceleration, and the speed performance may differ from the expected value
Usage example: create a script and place it in the object bar, copy the following "Example_ObjectLauncher_OnHomingFail" code in the script to save, run the game, and generate a Object Launcher, a sphere for emission, and an NPC target in the scene. Bind the delegate function for the corresponding event to the transmitter. Press key "1" to launch sphere and track NPC. The object code is set as follows:
@Component
export default class Example_ObjectLauncher_OnHomingFail extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a sphere at world coordinates (200, 0, 25)
let ball = await GameObject.asyncSpawn("84121") as Model;
ball.worldTransform.position = new Vector(200, 0, 25);
// Generate an NPC asynchronously at world coordinates (20001000130) and destroy it after 2 seconds.
let target = Player.spawnDefaultCharacter();
target.worldTransform.position = new Vector(2000, 1000, 130);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1000
myLauncher.initialSpeed = 1000;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set collision speed attenuation to 0.5
myLauncher.collisionVelocityRetention = 0.5;
// Delegate binding function for transmitter tracking failure, and print information in case of tracking failure
myLauncher.onProjectileHomingFail.add((projectile) => {
console.log("Homing Fail");
});
// Add a 'LAUNCHTOTARGET' event listener sent by the client, shoot the ball diagonally upwards and track NPCs.
Event.addClientListener("LAUNCHTOTARGET", () => {
TimeUtil.delaySecond(1).then(() => {
target.destroy();
});
myLauncher.spawnProjectileInstanceLaunchToTarget(ball.gameObjectId, target, 2000, ball.worldTransform.position, new Vector(1, 0, 1));
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a button method: Press button "1" to send a "LAUNCHTOTARGET" event to the server and launch a ball to track the NPC.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCHTOTARGET");
});
}
}
}
@Component
export default class Example_ObjectLauncher_OnHomingFail extends Script {
protected async onStart(): Promise<void> {
// The following logic is executed on the server side
if(SystemUtil.isServer()) {
// Asynchronously generate a sphere at world coordinates (200, 0, 25)
let ball = await GameObject.asyncSpawn("84121") as Model;
ball.worldTransform.position = new Vector(200, 0, 25);
// Generate an NPC asynchronously at world coordinates (20001000130) and destroy it after 2 seconds.
let target = Player.spawnDefaultCharacter();
target.worldTransform.position = new Vector(2000, 1000, 130);
// Asynchronous generate Object Launcher
let myLauncher = await GameObject.asyncSpawn("ObjectLauncher") as ObjectLauncher;
// Set the initial launch speed to 1000
myLauncher.initialSpeed = 1000;
// Set the collision radius to 25
myLauncher.capsuleRadius = 25;
// Set collision half length to 25
myLauncher.capsuleHalfLength = 25;
// Activate rebound
myLauncher.isShouldBounce = true;
// Set collision speed attenuation to 0.5
myLauncher.collisionVelocityRetention = 0.5;
// Delegate binding function for transmitter tracking failure, and print information in case of tracking failure
myLauncher.onProjectileHomingFail.add((projectile) => {
console.log("Homing Fail");
});
// Add a 'LAUNCHTOTARGET' event listener sent by the client, shoot the ball diagonally upwards and track NPCs.
Event.addClientListener("LAUNCHTOTARGET", () => {
TimeUtil.delaySecond(1).then(() => {
target.destroy();
});
myLauncher.spawnProjectileInstanceLaunchToTarget(ball.gameObjectId, target, 2000, ball.worldTransform.position, new Vector(1, 0, 1));
});
}
// The following logic is executed on the client side
if(SystemUtil.isClient()) {
// Add a button method: Press button "1" to send a "LAUNCHTOTARGET" event to the server and launch a ball to track the NPC.
InputUtil.onKeyDown(Keys.One, () => {
Event.dispatchToServer("LAUNCHTOTARGET");
});
}
}
}