Skip to content

Commit 406d23b

Browse files
d2kkStuyk
andauthored
refactor: Enhance vehicle repair function to restore health and attributes (#176)
* refactor: Enhance vehicle repair function to restore health and attributes * Update src/main/server/vehicle/index.ts Co-authored-by: Stuyk <trevorwessel@protonmail.com> --------- Co-authored-by: Stuyk <trevorwessel@protonmail.com>
1 parent fcffaff commit 406d23b

File tree

1 file changed

+47
-15
lines changed

1 file changed

+47
-15
lines changed

src/main/server/vehicle/index.ts

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -211,32 +211,64 @@ export function useVehicle(vehicle: alt.Vehicle) {
211211
}
212212

213213
/**
214-
* Despawns current vehicle, grabs existing document on the vehicle.
215-
* Recreates the vehicle, saves health, and then re-applies the document.
214+
* Repairs the current vehicle by recreating it with saved attributes,
215+
* applying the existing document, and restoring its health.
216216
*
217-
* @return
217+
* @return {Promise<alt.Vehicle>} The repaired vehicle instance.
218218
*/
219219
async function repair(): Promise<alt.Vehicle> {
220220
const document = useVehicleDocument(vehicle);
221-
const model = vehicle.model;
222-
const pos = vehicle.pos;
223-
const rot = vehicle.rot;
224-
225-
try {
226-
vehicle.destroy();
227-
} catch (err) {}
228-
229-
vehicle = new alt.Vehicle(model, pos, rot);
230221

222+
// If no document is available, return the original vehicle
231223
if (!document.get()) {
232224
return vehicle;
233225
}
234226

235-
useVehicleBinder(vehicle).bind(document.get(), false);
227+
const { model, pos, rot } = vehicle;
228+
229+
// Create a new vehicle instance
230+
const newVehicle = new alt.Vehicle(model, pos, rot);
231+
if (!newVehicle) {
232+
throw new Error('Failed to create a new vehicle instance.');
233+
}
234+
235+
// Bind the document to the new vehicle
236+
useVehicleBinder(newVehicle).bind(document.get(), true);
237+
238+
// Set vehicle health to maximum
239+
const MAX_HEALTH = 1000;
240+
Object.assign(newVehicle, {
241+
bodyHealth: MAX_HEALTH,
242+
engineHealth: MAX_HEALTH,
243+
petrolTankHealth: MAX_HEALTH,
244+
});
245+
246+
// Repair windows and reset damage
247+
for (let i = 0; i < 7; i++) {
248+
if (newVehicle.hasArmoredWindows) {
249+
newVehicle.setArmoredWindowHealth(i, MAX_HEALTH);
250+
} else {
251+
newVehicle.setWindowDamaged(i, false);
252+
}
253+
}
254+
255+
// Repair all wheels
256+
Array.from({ length: newVehicle.wheelsCount }).forEach((_, i) =>
257+
newVehicle.setWheelFixed(i)
258+
);
259+
260+
// Save the updated vehicle state
236261
await save();
237-
sync();
238262

239-
return vehicle;
263+
// Destroy the old vehicle safely
264+
try {
265+
vehicle.destroy();
266+
} catch (err) {
267+
console.warn('Error destroying the old vehicle:', err);
268+
}
269+
270+
vehicle = newVehicle;
271+
return newVehicle;
240272
}
241273

242274
/**

0 commit comments

Comments
 (0)